babylon.max.js 4.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  441. // Rebuild shaders source code
  442. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  443. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  444. vertexCode = prefix + vertexCode;
  445. fragmentCode = prefix + fragmentCode;
  446. // Number lines of shaders source code
  447. var i = 2;
  448. var regex = /\n/gm;
  449. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. i = 2;
  451. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. // Dump shaders name and formatted source code
  453. if (this.name.vertexElement) {
  454. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  455. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  456. }
  457. else if (this.name.vertex) {
  458. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  459. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  460. }
  461. else {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  464. }
  465. };
  466. ;
  467. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  468. var preparedSourceCode = this._processPrecision(sourceCode);
  469. if (this._engine.webGLVersion == 1) {
  470. callback(preparedSourceCode);
  471. return;
  472. }
  473. // Already converted
  474. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  475. callback(preparedSourceCode.replace("#version 300 es", ""));
  476. return;
  477. }
  478. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  479. // Remove extensions
  480. // #extension GL_OES_standard_derivatives : enable
  481. // #extension GL_EXT_shader_texture_lod : enable
  482. // #extension GL_EXT_frag_depth : enable
  483. // #extension GL_EXT_draw_buffers : require
  484. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  485. var result = preparedSourceCode.replace(regex, "");
  486. // Migrate to GLSL v300
  487. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  488. result = result.replace(/attribute[ \t]/g, "in ");
  489. result = result.replace(/[ \t]attribute/g, " in");
  490. if (isFragment) {
  491. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  492. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/texture2D\s*\(/g, "texture(");
  494. result = result.replace(/textureCube\s*\(/g, "texture(");
  495. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  496. result = result.replace(/gl_FragColor/g, "glFragColor");
  497. result = result.replace(/gl_FragData/g, "glFragData");
  498. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  499. }
  500. callback(result);
  501. };
  502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  503. var _this = this;
  504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  505. var match = regex.exec(sourceCode);
  506. var returnValue = new String(sourceCode);
  507. while (match != null) {
  508. var includeFile = match[1];
  509. // Uniform declaration
  510. if (includeFile.indexOf("__decl__") !== -1) {
  511. includeFile = includeFile.replace(/__decl__/, "");
  512. if (this._engine.supportsUniformBuffers) {
  513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  515. }
  516. includeFile = includeFile + "Declaration";
  517. }
  518. if (Effect.IncludesShadersStore[includeFile]) {
  519. // Substitution
  520. var includeContent = Effect.IncludesShadersStore[includeFile];
  521. if (match[2]) {
  522. var splits = match[3].split(",");
  523. for (var index = 0; index < splits.length; index += 2) {
  524. var source = new RegExp(splits[index], "g");
  525. var dest = splits[index + 1];
  526. includeContent = includeContent.replace(source, dest);
  527. }
  528. }
  529. if (match[4]) {
  530. var indexString = match[5];
  531. if (indexString.indexOf("..") !== -1) {
  532. var indexSplits = indexString.split("..");
  533. var minIndex = parseInt(indexSplits[0]);
  534. var maxIndex = parseInt(indexSplits[1]);
  535. var sourceIncludeContent = includeContent.slice(0);
  536. includeContent = "";
  537. if (isNaN(maxIndex)) {
  538. maxIndex = this._indexParameters[indexSplits[1]];
  539. }
  540. for (var i = minIndex; i < maxIndex; i++) {
  541. if (!this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  548. }
  549. }
  550. else {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  558. }
  559. }
  560. // Replace
  561. returnValue = returnValue.replace(match[0], includeContent);
  562. }
  563. else {
  564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  565. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  566. Effect.IncludesShadersStore[includeFile] = fileContent;
  567. _this._processIncludes(returnValue, callback);
  568. });
  569. return;
  570. }
  571. match = regex.exec(sourceCode);
  572. }
  573. callback(returnValue);
  574. };
  575. Effect.prototype._processPrecision = function (source) {
  576. if (source.indexOf("precision highp float") === -1) {
  577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  578. source = "precision mediump float;\n" + source;
  579. }
  580. else {
  581. source = "precision highp float;\n" + source;
  582. }
  583. }
  584. else {
  585. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  586. source = source.replace("precision highp float", "precision mediump float");
  587. }
  588. }
  589. return source;
  590. };
  591. /**
  592. * Recompiles the webGL program
  593. * @param vertexSourceCode The source code for the vertex shader.
  594. * @param fragmentSourceCode The source code for the fragment shader.
  595. * @param onCompiled Callback called when completed.
  596. * @param onError Callback called on error.
  597. */
  598. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  599. var _this = this;
  600. this._isReady = false;
  601. this._vertexSourceCodeOverride = vertexSourceCode;
  602. this._fragmentSourceCodeOverride = fragmentSourceCode;
  603. this.onError = function (effect, error) {
  604. if (onError) {
  605. onError(error);
  606. }
  607. };
  608. this.onCompiled = function () {
  609. var scenes = _this.getEngine().scenes;
  610. for (var i = 0; i < scenes.length; i++) {
  611. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  612. }
  613. if (onCompiled) {
  614. onCompiled(_this._program);
  615. }
  616. };
  617. this._fallbacks = null;
  618. this._prepareEffect();
  619. };
  620. /**
  621. * Gets the uniform locations of the the specified variable names
  622. * @param names THe names of the variables to lookup.
  623. * @returns Array of locations in the same order as variable names.
  624. */
  625. Effect.prototype.getSpecificUniformLocations = function (names) {
  626. var engine = this._engine;
  627. return engine.getUniforms(this._program, names);
  628. };
  629. /**
  630. * Prepares the effect
  631. */
  632. Effect.prototype._prepareEffect = function () {
  633. var attributesNames = this._attributesNames;
  634. var defines = this.defines;
  635. var fallbacks = this._fallbacks;
  636. this._valueCache = {};
  637. var previousProgram = this._program;
  638. try {
  639. var engine = this._engine;
  640. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  641. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  642. }
  643. else {
  644. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  645. }
  646. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  647. if (engine.supportsUniformBuffers) {
  648. for (var name in this._uniformBuffersNames) {
  649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  650. }
  651. }
  652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  653. this._attributes = engine.getAttributes(this._program, attributesNames);
  654. var index;
  655. for (index = 0; index < this._samplers.length; index++) {
  656. var sampler = this.getUniform(this._samplers[index]);
  657. if (sampler == null) {
  658. this._samplers.splice(index, 1);
  659. index--;
  660. }
  661. }
  662. engine.bindSamplers(this);
  663. this._compilationError = "";
  664. this._isReady = true;
  665. if (this.onCompiled) {
  666. this.onCompiled(this);
  667. }
  668. this.onCompileObservable.notifyObservers(this);
  669. this.onCompileObservable.clear();
  670. // Unbind mesh reference in fallbacks
  671. if (this._fallbacks) {
  672. this._fallbacks.unBindMesh();
  673. }
  674. if (previousProgram) {
  675. this.getEngine()._deleteProgram(previousProgram);
  676. }
  677. }
  678. catch (e) {
  679. this._compilationError = e.message;
  680. // Let's go through fallbacks then
  681. BABYLON.Tools.Error("Unable to compile effect:");
  682. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  683. return " " + uniform;
  684. }));
  685. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  686. return " " + attribute;
  687. }));
  688. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. /**
  1369. * Ray from a pointer if availible (eg. 6dof controller)
  1370. */
  1371. _this.ray = null;
  1372. _this.skipOnPointerObservable = false;
  1373. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1374. return _this;
  1375. }
  1376. return PointerInfoPre;
  1377. }(PointerInfoBase));
  1378. BABYLON.PointerInfoPre = PointerInfoPre;
  1379. /**
  1380. * This type contains all the data related to a pointer event in Babylon.js.
  1381. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1382. */
  1383. var PointerInfo = /** @class */ (function (_super) {
  1384. __extends(PointerInfo, _super);
  1385. function PointerInfo(type, event, pickInfo) {
  1386. var _this = _super.call(this, type, event) || this;
  1387. _this.pickInfo = pickInfo;
  1388. return _this;
  1389. }
  1390. return PointerInfo;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfo = PointerInfo;
  1393. })(BABYLON || (BABYLON = {}));
  1394. //# sourceMappingURL=babylon.pointerEvents.js.map
  1395. var BABYLON;
  1396. (function (BABYLON) {
  1397. BABYLON.ToGammaSpace = 1 / 2.2;
  1398. BABYLON.ToLinearSpace = 2.2;
  1399. BABYLON.Epsilon = 0.001;
  1400. /**
  1401. * Class used to hold a RBG color
  1402. */
  1403. var Color3 = /** @class */ (function () {
  1404. /**
  1405. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1406. * @param r defines the red component (between 0 and 1, default is 0)
  1407. * @param g defines the green component (between 0 and 1, default is 0)
  1408. * @param b defines the blue component (between 0 and 1, default is 0)
  1409. */
  1410. function Color3(
  1411. /**
  1412. * Defines the red component (between 0 and 1, default is 0)
  1413. */
  1414. r,
  1415. /**
  1416. * Defines the green component (between 0 and 1, default is 0)
  1417. */
  1418. g,
  1419. /**
  1420. * Defines the blue component (between 0 and 1, default is 0)
  1421. */
  1422. b) {
  1423. if (r === void 0) { r = 0; }
  1424. if (g === void 0) { g = 0; }
  1425. if (b === void 0) { b = 0; }
  1426. this.r = r;
  1427. this.g = g;
  1428. this.b = b;
  1429. }
  1430. /**
  1431. * Creates a string with the Color3 current values
  1432. * @returns the string representation of the Color3 object
  1433. */
  1434. Color3.prototype.toString = function () {
  1435. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1436. };
  1437. /**
  1438. * Returns the string "Color3"
  1439. * @returns "Color3"
  1440. */
  1441. Color3.prototype.getClassName = function () {
  1442. return "Color3";
  1443. };
  1444. /**
  1445. * Compute the Color3 hash code
  1446. * @returns an unique number that can be used to hash Color3 objects
  1447. */
  1448. Color3.prototype.getHashCode = function () {
  1449. var hash = this.r || 0;
  1450. hash = (hash * 397) ^ (this.g || 0);
  1451. hash = (hash * 397) ^ (this.b || 0);
  1452. return hash;
  1453. };
  1454. // Operators
  1455. /**
  1456. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1457. * @param array defines the array where to store the r,g,b components
  1458. * @param index defines an optional index in the target array to define where to start storing values
  1459. * @returns the current Color3 object
  1460. */
  1461. Color3.prototype.toArray = function (array, index) {
  1462. if (index === undefined) {
  1463. index = 0;
  1464. }
  1465. array[index] = this.r;
  1466. array[index + 1] = this.g;
  1467. array[index + 2] = this.b;
  1468. return this;
  1469. };
  1470. /**
  1471. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1472. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1473. * @returns a new {BABYLON.Color4} object
  1474. */
  1475. Color3.prototype.toColor4 = function (alpha) {
  1476. if (alpha === void 0) { alpha = 1; }
  1477. return new Color4(this.r, this.g, this.b, alpha);
  1478. };
  1479. /**
  1480. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1481. * @returns the new array
  1482. */
  1483. Color3.prototype.asArray = function () {
  1484. var result = new Array();
  1485. this.toArray(result, 0);
  1486. return result;
  1487. };
  1488. /**
  1489. * Returns the luminance value
  1490. * @returns a float value
  1491. */
  1492. Color3.prototype.toLuminance = function () {
  1493. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1494. };
  1495. /**
  1496. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1497. * @param otherColor defines the second operand
  1498. * @returns the new Color3 object
  1499. */
  1500. Color3.prototype.multiply = function (otherColor) {
  1501. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1502. };
  1503. /**
  1504. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1505. * @param otherColor defines the second operand
  1506. * @param result defines the Color3 object where to store the result
  1507. * @returns the current Color3
  1508. */
  1509. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1510. result.r = this.r * otherColor.r;
  1511. result.g = this.g * otherColor.g;
  1512. result.b = this.b * otherColor.b;
  1513. return this;
  1514. };
  1515. /**
  1516. * Determines equality between Color3 objects
  1517. * @param otherColor defines the second operand
  1518. * @returns true if the rgb values are equal to the given ones
  1519. */
  1520. Color3.prototype.equals = function (otherColor) {
  1521. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1522. };
  1523. /**
  1524. * Determines equality between the current Color3 object and a set of r,b,g values
  1525. * @param r defines the red component to check
  1526. * @param g defines the green component to check
  1527. * @param b defines the blue component to check
  1528. * @returns true if the rgb values are equal to the given ones
  1529. */
  1530. Color3.prototype.equalsFloats = function (r, g, b) {
  1531. return this.r === r && this.g === g && this.b === b;
  1532. };
  1533. /**
  1534. * Multiplies in place each rgb value by scale
  1535. * @param scale defines the scaling factor
  1536. * @returns the updated Color3
  1537. */
  1538. Color3.prototype.scale = function (scale) {
  1539. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1540. };
  1541. /**
  1542. * Multiplies the rgb values by scale and stores the result into "result"
  1543. * @param scale defines the scaling factor
  1544. * @param result defines the Color3 object where to store the result
  1545. * @returns the unmodified current Color3
  1546. */
  1547. Color3.prototype.scaleToRef = function (scale, result) {
  1548. result.r = this.r * scale;
  1549. result.g = this.g * scale;
  1550. result.b = this.b * scale;
  1551. return this;
  1552. };
  1553. /**
  1554. * Scale the current Color3 values by a factor and add the result to a given Color3
  1555. * @param scale defines the scale factor
  1556. * @param result defines color to store the result into
  1557. * @returns the unmodified current Color3
  1558. */
  1559. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1560. result.r += this.r * scale;
  1561. result.g += this.g * scale;
  1562. result.b += this.b * scale;
  1563. return this;
  1564. };
  1565. /**
  1566. * Clamps the rgb values by the min and max values and stores the result into "result"
  1567. * @param min defines minimum clamping value (default is 0)
  1568. * @param max defines maximum clamping value (default is 1)
  1569. * @param result defines color to store the result into
  1570. * @returns the original Color3
  1571. */
  1572. Color3.prototype.clampToRef = function (min, max, result) {
  1573. if (min === void 0) { min = 0; }
  1574. if (max === void 0) { max = 1; }
  1575. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1576. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1577. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1578. return this;
  1579. };
  1580. /**
  1581. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1582. * @param otherColor defines the second operand
  1583. * @returns the new Color3
  1584. */
  1585. Color3.prototype.add = function (otherColor) {
  1586. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1587. };
  1588. /**
  1589. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1590. * @param otherColor defines the second operand
  1591. * @param result defines Color3 object to store the result into
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.addToRef = function (otherColor, result) {
  1595. result.r = this.r + otherColor.r;
  1596. result.g = this.g + otherColor.g;
  1597. result.b = this.b + otherColor.b;
  1598. return this;
  1599. };
  1600. /**
  1601. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1602. * @param otherColor defines the second operand
  1603. * @returns the new Color3
  1604. */
  1605. Color3.prototype.subtract = function (otherColor) {
  1606. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1607. };
  1608. /**
  1609. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1610. * @param otherColor defines the second operand
  1611. * @param result defines Color3 object to store the result into
  1612. * @returns the unmodified current Color3
  1613. */
  1614. Color3.prototype.subtractToRef = function (otherColor, result) {
  1615. result.r = this.r - otherColor.r;
  1616. result.g = this.g - otherColor.g;
  1617. result.b = this.b - otherColor.b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Copy the current object
  1622. * @returns a new Color3 copied the current one
  1623. */
  1624. Color3.prototype.clone = function () {
  1625. return new Color3(this.r, this.g, this.b);
  1626. };
  1627. /**
  1628. * Copies the rgb values from the source in the current Color3
  1629. * @param source defines the source Color3 object
  1630. * @returns the updated Color3 object
  1631. */
  1632. Color3.prototype.copyFrom = function (source) {
  1633. this.r = source.r;
  1634. this.g = source.g;
  1635. this.b = source.b;
  1636. return this;
  1637. };
  1638. /**
  1639. * Updates the Color3 rgb values from the given floats
  1640. * @param r defines the red component to read from
  1641. * @param g defines the green component to read from
  1642. * @param b defines the blue component to read from
  1643. * @returns the current Color3 object
  1644. */
  1645. Color3.prototype.copyFromFloats = function (r, g, b) {
  1646. this.r = r;
  1647. this.g = g;
  1648. this.b = b;
  1649. return this;
  1650. };
  1651. /**
  1652. * Updates the Color3 rgb values from the given floats
  1653. * @param r defines the red component to read from
  1654. * @param g defines the green component to read from
  1655. * @param b defines the blue component to read from
  1656. * @returns the current Color3 object
  1657. */
  1658. Color3.prototype.set = function (r, g, b) {
  1659. return this.copyFromFloats(r, g, b);
  1660. };
  1661. /**
  1662. * Compute the Color3 hexadecimal code as a string
  1663. * @returns a string containing the hexadecimal representation of the Color3 object
  1664. */
  1665. Color3.prototype.toHexString = function () {
  1666. var intR = (this.r * 255) | 0;
  1667. var intG = (this.g * 255) | 0;
  1668. var intB = (this.b * 255) | 0;
  1669. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1670. };
  1671. /**
  1672. * Computes a new Color3 converted from the current one to linear space
  1673. * @returns a new Color3 object
  1674. */
  1675. Color3.prototype.toLinearSpace = function () {
  1676. var convertedColor = new Color3();
  1677. this.toLinearSpaceToRef(convertedColor);
  1678. return convertedColor;
  1679. };
  1680. /**
  1681. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1682. * @param convertedColor defines the Color3 object where to store the linear space version
  1683. * @returns the unmodified Color3
  1684. */
  1685. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1686. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1687. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1688. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1689. return this;
  1690. };
  1691. /**
  1692. * Computes a new Color3 converted from the current one to gamma space
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.prototype.toGammaSpace = function () {
  1696. var convertedColor = new Color3();
  1697. this.toGammaSpaceToRef(convertedColor);
  1698. return convertedColor;
  1699. };
  1700. /**
  1701. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1702. * @param convertedColor defines the Color3 object where to store the gamma space version
  1703. * @returns the unmodified Color3
  1704. */
  1705. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1706. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1707. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1708. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1709. return this;
  1710. };
  1711. // Statics
  1712. /**
  1713. * Creates a new Color3 from the string containing valid hexadecimal values
  1714. * @param hex defines a string containing valid hexadecimal values
  1715. * @returns a new Color3 object
  1716. */
  1717. Color3.FromHexString = function (hex) {
  1718. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1719. return new Color3(0, 0, 0);
  1720. }
  1721. var r = parseInt(hex.substring(1, 3), 16);
  1722. var g = parseInt(hex.substring(3, 5), 16);
  1723. var b = parseInt(hex.substring(5, 7), 16);
  1724. return Color3.FromInts(r, g, b);
  1725. };
  1726. /**
  1727. * Creates a new Vector3 from the starting index of the given array
  1728. * @param array defines the source array
  1729. * @param offset defines an offset in the source array
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.FromArray = function (array, offset) {
  1733. if (offset === void 0) { offset = 0; }
  1734. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1735. };
  1736. /**
  1737. * Creates a new Color3 from integer values (< 256)
  1738. * @param r defines the red component to read from (value between 0 and 255)
  1739. * @param g defines the green component to read from (value between 0 and 255)
  1740. * @param b defines the blue component to read from (value between 0 and 255)
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromInts = function (r, g, b) {
  1744. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1745. };
  1746. /**
  1747. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1748. * @param start defines the start Color3 value
  1749. * @param end defines the end Color3 value
  1750. * @param amount defines the gradient value between start and end
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.Lerp = function (start, end, amount) {
  1754. var r = start.r + ((end.r - start.r) * amount);
  1755. var g = start.g + ((end.g - start.g) * amount);
  1756. var b = start.b + ((end.b - start.b) * amount);
  1757. return new Color3(r, g, b);
  1758. };
  1759. /**
  1760. * Returns a Color3 value containing a red color
  1761. * @returns a new Color3 object
  1762. */
  1763. Color3.Red = function () { return new Color3(1, 0, 0); };
  1764. /**
  1765. * Returns a Color3 value containing a green color
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.Green = function () { return new Color3(0, 1, 0); };
  1769. /**
  1770. * Returns a Color3 value containing a blue color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1774. /**
  1775. * Returns a Color3 value containing a black color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Black = function () { return new Color3(0, 0, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a white color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.White = function () { return new Color3(1, 1, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a purple color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1789. /**
  1790. * Returns a Color3 value containing a magenta color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a yellow color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1799. /**
  1800. * Returns a Color3 value containing a gray color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1804. /**
  1805. * Returns a Color3 value containing a teal color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1809. /**
  1810. * Returns a Color3 value containing a random color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1814. return Color3;
  1815. }());
  1816. BABYLON.Color3 = Color3;
  1817. /**
  1818. * Class used to hold a RBGA color
  1819. */
  1820. var Color4 = /** @class */ (function () {
  1821. /**
  1822. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1823. * @param r defines the red component (between 0 and 1, default is 0)
  1824. * @param g defines the green component (between 0 and 1, default is 0)
  1825. * @param b defines the blue component (between 0 and 1, default is 0)
  1826. * @param a defines the alpha component (between 0 and 1, default is 1)
  1827. */
  1828. function Color4(
  1829. /**
  1830. * Defines the red component (between 0 and 1, default is 0)
  1831. */
  1832. r,
  1833. /**
  1834. * Defines the green component (between 0 and 1, default is 0)
  1835. */
  1836. g,
  1837. /**
  1838. * Defines the blue component (between 0 and 1, default is 0)
  1839. */
  1840. b,
  1841. /**
  1842. * Defines the alpha component (between 0 and 1, default is 1)
  1843. */
  1844. a) {
  1845. if (r === void 0) { r = 0; }
  1846. if (g === void 0) { g = 0; }
  1847. if (b === void 0) { b = 0; }
  1848. if (a === void 0) { a = 1; }
  1849. this.r = r;
  1850. this.g = g;
  1851. this.b = b;
  1852. this.a = a;
  1853. }
  1854. // Operators
  1855. /**
  1856. * Adds in place the given Color4 values to the current Color4 object
  1857. * @param right defines the second operand
  1858. * @returns the current updated Color4 object
  1859. */
  1860. Color4.prototype.addInPlace = function (right) {
  1861. this.r += right.r;
  1862. this.g += right.g;
  1863. this.b += right.b;
  1864. this.a += right.a;
  1865. return this;
  1866. };
  1867. /**
  1868. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1869. * @returns the new array
  1870. */
  1871. Color4.prototype.asArray = function () {
  1872. var result = new Array();
  1873. this.toArray(result, 0);
  1874. return result;
  1875. };
  1876. /**
  1877. * Stores from the starting index in the given array the Color4 successive values
  1878. * @param array defines the array where to store the r,g,b components
  1879. * @param index defines an optional index in the target array to define where to start storing values
  1880. * @returns the current Color4 object
  1881. */
  1882. Color4.prototype.toArray = function (array, index) {
  1883. if (index === undefined) {
  1884. index = 0;
  1885. }
  1886. array[index] = this.r;
  1887. array[index + 1] = this.g;
  1888. array[index + 2] = this.b;
  1889. array[index + 3] = this.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1894. * @param right defines the second operand
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.add = function (right) {
  1898. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1899. };
  1900. /**
  1901. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1902. * @param right defines the second operand
  1903. * @returns a new Color4 object
  1904. */
  1905. Color4.prototype.subtract = function (right) {
  1906. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1907. };
  1908. /**
  1909. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1910. * @param right defines the second operand
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the current Color4 object
  1913. */
  1914. Color4.prototype.subtractToRef = function (right, result) {
  1915. result.r = this.r - right.r;
  1916. result.g = this.g - right.g;
  1917. result.b = this.b - right.b;
  1918. result.a = this.a - right.a;
  1919. return this;
  1920. };
  1921. /**
  1922. * Creates a new Color4 with the current Color4 values multiplied by scale
  1923. * @param scale defines the scaling factor to apply
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.scale = function (scale) {
  1927. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1928. };
  1929. /**
  1930. * Multiplies the current Color4 values by scale and stores the result in "result"
  1931. * @param scale defines the scaling factor to apply
  1932. * @param result defines the Color4 object where to store the result
  1933. * @returns the current unmodified Color4
  1934. */
  1935. Color4.prototype.scaleToRef = function (scale, result) {
  1936. result.r = this.r * scale;
  1937. result.g = this.g * scale;
  1938. result.b = this.b * scale;
  1939. result.a = this.a * scale;
  1940. return this;
  1941. };
  1942. /**
  1943. * Scale the current Color4 values by a factor and add the result to a given Color4
  1944. * @param scale defines the scale factor
  1945. * @param result defines the Color4 object where to store the result
  1946. * @returns the unmodified current Color4
  1947. */
  1948. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1949. result.r += this.r * scale;
  1950. result.g += this.g * scale;
  1951. result.b += this.b * scale;
  1952. result.a += this.a * scale;
  1953. return this;
  1954. };
  1955. /**
  1956. * Clamps the rgb values by the min and max values and stores the result into "result"
  1957. * @param min defines minimum clamping value (default is 0)
  1958. * @param max defines maximum clamping value (default is 1)
  1959. * @param result defines color to store the result into.
  1960. * @returns the cuurent Color4
  1961. */
  1962. Color4.prototype.clampToRef = function (min, max, result) {
  1963. if (min === void 0) { min = 0; }
  1964. if (max === void 0) { max = 1; }
  1965. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1966. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1967. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1968. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1969. return this;
  1970. };
  1971. /**
  1972. * Multipy an Color4 value by another and return a new Color4 object
  1973. * @param color defines the Color4 value to multiply by
  1974. * @returns a new Color4 object
  1975. */
  1976. Color4.prototype.multiply = function (color) {
  1977. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1978. };
  1979. /**
  1980. * Multipy a Color4 value by another and push the result in a reference value
  1981. * @param color defines the Color4 value to multiply by
  1982. * @param result defines the Color4 to fill the result in
  1983. * @returns the result Color4
  1984. */
  1985. Color4.prototype.multiplyToRef = function (color, result) {
  1986. result.r = this.r * color.r;
  1987. result.g = this.g * color.g;
  1988. result.b = this.b * color.b;
  1989. result.a = this.a * color.a;
  1990. return result;
  1991. };
  1992. /**
  1993. * Creates a string with the Color4 current values
  1994. * @returns the string representation of the Color4 object
  1995. */
  1996. Color4.prototype.toString = function () {
  1997. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1998. };
  1999. /**
  2000. * Returns the string "Color4"
  2001. * @returns "Color4"
  2002. */
  2003. Color4.prototype.getClassName = function () {
  2004. return "Color4";
  2005. };
  2006. /**
  2007. * Compute the Color4 hash code
  2008. * @returns an unique number that can be used to hash Color4 objects
  2009. */
  2010. Color4.prototype.getHashCode = function () {
  2011. var hash = this.r || 0;
  2012. hash = (hash * 397) ^ (this.g || 0);
  2013. hash = (hash * 397) ^ (this.b || 0);
  2014. hash = (hash * 397) ^ (this.a || 0);
  2015. return hash;
  2016. };
  2017. /**
  2018. * Creates a new Color4 copied from the current one
  2019. * @returns a new Color4 object
  2020. */
  2021. Color4.prototype.clone = function () {
  2022. return new Color4(this.r, this.g, this.b, this.a);
  2023. };
  2024. /**
  2025. * Copies the given Color4 values into the current one
  2026. * @param source defines the source Color4 object
  2027. * @returns the current updated Color4 object
  2028. */
  2029. Color4.prototype.copyFrom = function (source) {
  2030. this.r = source.r;
  2031. this.g = source.g;
  2032. this.b = source.b;
  2033. this.a = source.a;
  2034. return this;
  2035. };
  2036. /**
  2037. * Copies the given float values into the current one
  2038. * @param r defines the red component to read from
  2039. * @param g defines the green component to read from
  2040. * @param b defines the blue component to read from
  2041. * @param a defines the alpha component to read from
  2042. * @returns the current updated Color4 object
  2043. */
  2044. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2045. this.r = r;
  2046. this.g = g;
  2047. this.b = b;
  2048. this.a = a;
  2049. return this;
  2050. };
  2051. /**
  2052. * Copies the given float values into the current one
  2053. * @param r defines the red component to read from
  2054. * @param g defines the green component to read from
  2055. * @param b defines the blue component to read from
  2056. * @param a defines the alpha component to read from
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.set = function (r, g, b, a) {
  2060. return this.copyFromFloats(r, g, b, a);
  2061. };
  2062. /**
  2063. * Compute the Color4 hexadecimal code as a string
  2064. * @returns a string containing the hexadecimal representation of the Color4 object
  2065. */
  2066. Color4.prototype.toHexString = function () {
  2067. var intR = (this.r * 255) | 0;
  2068. var intG = (this.g * 255) | 0;
  2069. var intB = (this.b * 255) | 0;
  2070. var intA = (this.a * 255) | 0;
  2071. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2072. };
  2073. /**
  2074. * Computes a new Color4 converted from the current one to linear space
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.prototype.toLinearSpace = function () {
  2078. var convertedColor = new Color4();
  2079. this.toLinearSpaceToRef(convertedColor);
  2080. return convertedColor;
  2081. };
  2082. /**
  2083. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2084. * @param convertedColor defines the Color4 object where to store the linear space version
  2085. * @returns the unmodified Color4
  2086. */
  2087. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2088. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2089. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2090. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2091. convertedColor.a = this.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Computes a new Color4 converted from the current one to gamma space
  2096. * @returns a new Color4 object
  2097. */
  2098. Color4.prototype.toGammaSpace = function () {
  2099. var convertedColor = new Color4();
  2100. this.toGammaSpaceToRef(convertedColor);
  2101. return convertedColor;
  2102. };
  2103. /**
  2104. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2105. * @param convertedColor defines the Color4 object where to store the gamma space version
  2106. * @returns the unmodified Color4
  2107. */
  2108. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2109. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2110. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2111. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2112. convertedColor.a = this.a;
  2113. return this;
  2114. };
  2115. // Statics
  2116. /**
  2117. * Creates a new Color4 from the string containing valid hexadecimal values
  2118. * @param hex defines a string containing valid hexadecimal values
  2119. * @returns a new Color4 object
  2120. */
  2121. Color4.FromHexString = function (hex) {
  2122. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2123. return new Color4(0.0, 0.0, 0.0, 0.0);
  2124. }
  2125. var r = parseInt(hex.substring(1, 3), 16);
  2126. var g = parseInt(hex.substring(3, 5), 16);
  2127. var b = parseInt(hex.substring(5, 7), 16);
  2128. var a = parseInt(hex.substring(7, 9), 16);
  2129. return Color4.FromInts(r, g, b, a);
  2130. };
  2131. /**
  2132. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2133. * @param left defines the start value
  2134. * @param right defines the end value
  2135. * @param amount defines the gradient factor
  2136. * @returns a new Color4 object
  2137. */
  2138. Color4.Lerp = function (left, right, amount) {
  2139. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2140. Color4.LerpToRef(left, right, amount, result);
  2141. return result;
  2142. };
  2143. /**
  2144. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2145. * @param left defines the start value
  2146. * @param right defines the end value
  2147. * @param amount defines the gradient factor
  2148. * @param result defines the Color4 object where to store data
  2149. */
  2150. Color4.LerpToRef = function (left, right, amount, result) {
  2151. result.r = left.r + (right.r - left.r) * amount;
  2152. result.g = left.g + (right.g - left.g) * amount;
  2153. result.b = left.b + (right.b - left.b) * amount;
  2154. result.a = left.a + (right.a - left.a) * amount;
  2155. };
  2156. /**
  2157. * Creates a new Color4 from the starting index element of the given array
  2158. * @param array defines the source array to read from
  2159. * @param offset defines the offset in the source array
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.FromArray = function (array, offset) {
  2163. if (offset === void 0) { offset = 0; }
  2164. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2165. };
  2166. /**
  2167. * Creates a new Color3 from integer values (< 256)
  2168. * @param r defines the red component to read from (value between 0 and 255)
  2169. * @param g defines the green component to read from (value between 0 and 255)
  2170. * @param b defines the blue component to read from (value between 0 and 255)
  2171. * @param a defines the alpha component to read from (value between 0 and 255)
  2172. * @returns a new Color3 object
  2173. */
  2174. Color4.FromInts = function (r, g, b, a) {
  2175. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2176. };
  2177. /**
  2178. * Check the content of a given array and convert it to an array containing RGBA data
  2179. * If the original array was already containing count * 4 values then it is returned directly
  2180. * @param colors defines the array to check
  2181. * @param count defines the number of RGBA data to expect
  2182. * @returns an array containing count * 4 values (RGBA)
  2183. */
  2184. Color4.CheckColors4 = function (colors, count) {
  2185. // Check if color3 was used
  2186. if (colors.length === count * 3) {
  2187. var colors4 = [];
  2188. for (var index = 0; index < colors.length; index += 3) {
  2189. var newIndex = (index / 3) * 4;
  2190. colors4[newIndex] = colors[index];
  2191. colors4[newIndex + 1] = colors[index + 1];
  2192. colors4[newIndex + 2] = colors[index + 2];
  2193. colors4[newIndex + 3] = 1.0;
  2194. }
  2195. return colors4;
  2196. }
  2197. return colors;
  2198. };
  2199. return Color4;
  2200. }());
  2201. BABYLON.Color4 = Color4;
  2202. /**
  2203. * Class representing a vector containing 2 coordinates
  2204. */
  2205. var Vector2 = /** @class */ (function () {
  2206. /**
  2207. * Creates a new Vector2 from the given x and y coordinates
  2208. * @param x defines the first coordinate
  2209. * @param y defines the second coordinate
  2210. */
  2211. function Vector2(
  2212. /** defines the first coordinate */
  2213. x,
  2214. /** defines the second coordinate */
  2215. y) {
  2216. this.x = x;
  2217. this.y = y;
  2218. }
  2219. /**
  2220. * Gets a string with the Vector2 coordinates
  2221. * @returns a string with the Vector2 coordinates
  2222. */
  2223. Vector2.prototype.toString = function () {
  2224. return "{X: " + this.x + " Y:" + this.y + "}";
  2225. };
  2226. /**
  2227. * Gets class name
  2228. * @returns the string "Vector2"
  2229. */
  2230. Vector2.prototype.getClassName = function () {
  2231. return "Vector2";
  2232. };
  2233. /**
  2234. * Gets current vector hash code
  2235. * @returns the Vector2 hash code as a number
  2236. */
  2237. Vector2.prototype.getHashCode = function () {
  2238. var hash = this.x || 0;
  2239. hash = (hash * 397) ^ (this.y || 0);
  2240. return hash;
  2241. };
  2242. // Operators
  2243. /**
  2244. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2245. * @param array defines the source array
  2246. * @param index defines the offset in source array
  2247. * @returns the current Vector2
  2248. */
  2249. Vector2.prototype.toArray = function (array, index) {
  2250. if (index === void 0) { index = 0; }
  2251. array[index] = this.x;
  2252. array[index + 1] = this.y;
  2253. return this;
  2254. };
  2255. /**
  2256. * Copy the current vector to an array
  2257. * @returns a new array with 2 elements: the Vector2 coordinates.
  2258. */
  2259. Vector2.prototype.asArray = function () {
  2260. var result = new Array();
  2261. this.toArray(result, 0);
  2262. return result;
  2263. };
  2264. /**
  2265. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2266. * @param source defines the source Vector2
  2267. * @returns the current updated Vector2
  2268. */
  2269. Vector2.prototype.copyFrom = function (source) {
  2270. this.x = source.x;
  2271. this.y = source.y;
  2272. return this;
  2273. };
  2274. /**
  2275. * Sets the Vector2 coordinates with the given floats
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. * @returns the current updated Vector2
  2279. */
  2280. Vector2.prototype.copyFromFloats = function (x, y) {
  2281. this.x = x;
  2282. this.y = y;
  2283. return this;
  2284. };
  2285. /**
  2286. * Sets the Vector2 coordinates with the given floats
  2287. * @param x defines the first coordinate
  2288. * @param y defines the second coordinate
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.set = function (x, y) {
  2292. return this.copyFromFloats(x, y);
  2293. };
  2294. /**
  2295. * Add another vector with the current one
  2296. * @param otherVector defines the other vector
  2297. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2298. */
  2299. Vector2.prototype.add = function (otherVector) {
  2300. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2301. };
  2302. /**
  2303. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2304. * @param otherVector defines the other vector
  2305. * @param result defines the target vector
  2306. * @returns the unmodified current Vector2
  2307. */
  2308. Vector2.prototype.addToRef = function (otherVector, result) {
  2309. result.x = this.x + otherVector.x;
  2310. result.y = this.y + otherVector.y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2315. * @param otherVector defines the other vector
  2316. * @returns the current updated Vector2
  2317. */
  2318. Vector2.prototype.addInPlace = function (otherVector) {
  2319. this.x += otherVector.x;
  2320. this.y += otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2325. * @param otherVector defines the other vector
  2326. * @returns a new Vector2
  2327. */
  2328. Vector2.prototype.addVector3 = function (otherVector) {
  2329. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2330. };
  2331. /**
  2332. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2333. * @param otherVector defines the other vector
  2334. * @returns a new Vector2
  2335. */
  2336. Vector2.prototype.subtract = function (otherVector) {
  2337. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2338. };
  2339. /**
  2340. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2341. * @param otherVector defines the other vector
  2342. * @param result defines the target vector
  2343. * @returns the unmodified current Vector2
  2344. */
  2345. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2346. result.x = this.x - otherVector.x;
  2347. result.y = this.y - otherVector.y;
  2348. return this;
  2349. };
  2350. /**
  2351. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2352. * @param otherVector defines the other vector
  2353. * @returns the current updated Vector2
  2354. */
  2355. Vector2.prototype.subtractInPlace = function (otherVector) {
  2356. this.x -= otherVector.x;
  2357. this.y -= otherVector.y;
  2358. return this;
  2359. };
  2360. /**
  2361. * Multiplies in place the current Vector2 coordinates by the given ones
  2362. * @param otherVector defines the other vector
  2363. * @returns the current updated Vector2
  2364. */
  2365. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2366. this.x *= otherVector.x;
  2367. this.y *= otherVector.y;
  2368. return this;
  2369. };
  2370. /**
  2371. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2372. * @param otherVector defines the other vector
  2373. * @returns a new Vector2
  2374. */
  2375. Vector2.prototype.multiply = function (otherVector) {
  2376. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2377. };
  2378. /**
  2379. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2380. * @param otherVector defines the other vector
  2381. * @param result defines the target vector
  2382. * @returns the unmodified current Vector2
  2383. */
  2384. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2385. result.x = this.x * otherVector.x;
  2386. result.y = this.y * otherVector.y;
  2387. return this;
  2388. };
  2389. /**
  2390. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2391. * @param x defines the first coordinate
  2392. * @param y defines the second coordinate
  2393. * @returns a new Vector2
  2394. */
  2395. Vector2.prototype.multiplyByFloats = function (x, y) {
  2396. return new Vector2(this.x * x, this.y * y);
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.divide = function (otherVector) {
  2404. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2405. };
  2406. /**
  2407. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2408. * @param otherVector defines the other vector
  2409. * @param result defines the target vector
  2410. * @returns the unmodified current Vector2
  2411. */
  2412. Vector2.prototype.divideToRef = function (otherVector, result) {
  2413. result.x = this.x / otherVector.x;
  2414. result.y = this.y / otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Divides the current Vector3 coordinates by the given ones
  2419. * @param otherVector defines the other vector
  2420. * @returns the current updated Vector2
  2421. */
  2422. Vector2.prototype.divideInPlace = function (otherVector) {
  2423. return this.divideToRef(otherVector, this);
  2424. };
  2425. /**
  2426. * Gets a new Vector2 with current Vector2 negated coordinates
  2427. * @returns a new Vector2
  2428. */
  2429. Vector2.prototype.negate = function () {
  2430. return new Vector2(-this.x, -this.y);
  2431. };
  2432. /**
  2433. * Multiply the Vector2 coordinates by scale
  2434. * @param scale defines the scaling factor
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.scaleInPlace = function (scale) {
  2438. this.x *= scale;
  2439. this.y *= scale;
  2440. return this;
  2441. };
  2442. /**
  2443. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2444. * @param scale defines the scaling factor
  2445. * @returns a new Vector2
  2446. */
  2447. Vector2.prototype.scale = function (scale) {
  2448. var result = new Vector2(0, 0);
  2449. this.scaleToRef(scale, result);
  2450. return result;
  2451. };
  2452. /**
  2453. * Scale the current Vector2 values by a factor to a given Vector2
  2454. * @param scale defines the scale factor
  2455. * @param result defines the Vector2 object where to store the result
  2456. * @returns the unmodified current Vector2
  2457. */
  2458. Vector2.prototype.scaleToRef = function (scale, result) {
  2459. result.x = this.x * scale;
  2460. result.y = this.y * scale;
  2461. return this;
  2462. };
  2463. /**
  2464. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2465. * @param scale defines the scale factor
  2466. * @param result defines the Vector2 object where to store the result
  2467. * @returns the unmodified current Vector2
  2468. */
  2469. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2470. result.x += this.x * scale;
  2471. result.y += this.y * scale;
  2472. return this;
  2473. };
  2474. /**
  2475. * Gets a boolean if two vectors are equals
  2476. * @param otherVector defines the other vector
  2477. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2478. */
  2479. Vector2.prototype.equals = function (otherVector) {
  2480. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2481. };
  2482. /**
  2483. * Gets a boolean if two vectors are equals (using an epsilon value)
  2484. * @param otherVector defines the other vector
  2485. * @param epsilon defines the minimal distance to consider equality
  2486. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2487. */
  2488. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2489. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2490. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2491. };
  2492. // Properties
  2493. /**
  2494. * Gets the length of the vector
  2495. * @returns the vector length (float)
  2496. */
  2497. Vector2.prototype.length = function () {
  2498. return Math.sqrt(this.x * this.x + this.y * this.y);
  2499. };
  2500. /**
  2501. * Gets the vector squared length
  2502. * @returns the vector squared length (float)
  2503. */
  2504. Vector2.prototype.lengthSquared = function () {
  2505. return (this.x * this.x + this.y * this.y);
  2506. };
  2507. // Methods
  2508. /**
  2509. * Normalize the vector
  2510. * @returns the current updated Vector2
  2511. */
  2512. Vector2.prototype.normalize = function () {
  2513. var len = this.length();
  2514. if (len === 0)
  2515. return this;
  2516. var num = 1.0 / len;
  2517. this.x *= num;
  2518. this.y *= num;
  2519. return this;
  2520. };
  2521. /**
  2522. * Gets a new Vector2 copied from the Vector2
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.clone = function () {
  2526. return new Vector2(this.x, this.y);
  2527. };
  2528. // Statics
  2529. /**
  2530. * Gets a new Vector2(0, 0)
  2531. * @returns a new Vector2
  2532. */
  2533. Vector2.Zero = function () {
  2534. return new Vector2(0, 0);
  2535. };
  2536. /**
  2537. * Gets a new Vector2(1, 1)
  2538. * @returns a new Vector2
  2539. */
  2540. Vector2.One = function () {
  2541. return new Vector2(1, 1);
  2542. };
  2543. /**
  2544. * Gets a new Vector2 set from the given index element of the given array
  2545. * @param array defines the data source
  2546. * @param offset defines the offset in the data source
  2547. * @returns a new Vector2
  2548. */
  2549. Vector2.FromArray = function (array, offset) {
  2550. if (offset === void 0) { offset = 0; }
  2551. return new Vector2(array[offset], array[offset + 1]);
  2552. };
  2553. /**
  2554. * Sets "result" from the given index element of the given array
  2555. * @param array defines the data source
  2556. * @param offset defines the offset in the data source
  2557. * @param result defines the target vector
  2558. */
  2559. Vector2.FromArrayToRef = function (array, offset, result) {
  2560. result.x = array[offset];
  2561. result.y = array[offset + 1];
  2562. };
  2563. /**
  2564. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2565. * @param value1 defines 1st point of control
  2566. * @param value2 defines 2nd point of control
  2567. * @param value3 defines 3rd point of control
  2568. * @param value4 defines 4th point of control
  2569. * @param amount defines the interpolation factor
  2570. * @returns a new Vector2
  2571. */
  2572. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2573. var squared = amount * amount;
  2574. var cubed = amount * squared;
  2575. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2576. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2577. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2578. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2579. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2580. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2581. return new Vector2(x, y);
  2582. };
  2583. /**
  2584. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2585. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2586. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2587. * @param value defines the value to clamp
  2588. * @param min defines the lower limit
  2589. * @param max defines the upper limit
  2590. * @returns a new Vector2
  2591. */
  2592. Vector2.Clamp = function (value, min, max) {
  2593. var x = value.x;
  2594. x = (x > max.x) ? max.x : x;
  2595. x = (x < min.x) ? min.x : x;
  2596. var y = value.y;
  2597. y = (y > max.y) ? max.y : y;
  2598. y = (y < min.y) ? min.y : y;
  2599. return new Vector2(x, y);
  2600. };
  2601. /**
  2602. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2603. * @param value1 defines the 1st control point
  2604. * @param tangent1 defines the outgoing tangent
  2605. * @param value2 defines the 2nd control point
  2606. * @param tangent2 defines the incoming tangent
  2607. * @param amount defines the interpolation factor
  2608. * @returns a new Vector2
  2609. */
  2610. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2611. var squared = amount * amount;
  2612. var cubed = amount * squared;
  2613. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2614. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2615. var part3 = (cubed - (2.0 * squared)) + amount;
  2616. var part4 = cubed - squared;
  2617. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2618. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2619. return new Vector2(x, y);
  2620. };
  2621. /**
  2622. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2623. * @param start defines the start vector
  2624. * @param end defines the end vector
  2625. * @param amount defines the interpolation factor
  2626. * @returns a new Vector2
  2627. */
  2628. Vector2.Lerp = function (start, end, amount) {
  2629. var x = start.x + ((end.x - start.x) * amount);
  2630. var y = start.y + ((end.y - start.y) * amount);
  2631. return new Vector2(x, y);
  2632. };
  2633. /**
  2634. * Gets the dot product of the vector "left" and the vector "right"
  2635. * @param left defines first vector
  2636. * @param right defines second vector
  2637. * @returns the dot product (float)
  2638. */
  2639. Vector2.Dot = function (left, right) {
  2640. return left.x * right.x + left.y * right.y;
  2641. };
  2642. /**
  2643. * Returns a new Vector2 equal to the normalized given vector
  2644. * @param vector defines the vector to normalize
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.Normalize = function (vector) {
  2648. var newVector = vector.clone();
  2649. newVector.normalize();
  2650. return newVector;
  2651. };
  2652. /**
  2653. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2654. * @param left defines 1st vector
  2655. * @param right defines 2nd vector
  2656. * @returns a new Vector2
  2657. */
  2658. Vector2.Minimize = function (left, right) {
  2659. var x = (left.x < right.x) ? left.x : right.x;
  2660. var y = (left.y < right.y) ? left.y : right.y;
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2665. * @param left defines 1st vector
  2666. * @param right defines 2nd vector
  2667. * @returns a new Vector2
  2668. */
  2669. Vector2.Maximize = function (left, right) {
  2670. var x = (left.x > right.x) ? left.x : right.x;
  2671. var y = (left.y > right.y) ? left.y : right.y;
  2672. return new Vector2(x, y);
  2673. };
  2674. /**
  2675. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2676. * @param vector defines the vector to transform
  2677. * @param transformation defines the matrix to apply
  2678. * @returns a new Vector2
  2679. */
  2680. Vector2.Transform = function (vector, transformation) {
  2681. var r = Vector2.Zero();
  2682. Vector2.TransformToRef(vector, transformation, r);
  2683. return r;
  2684. };
  2685. /**
  2686. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2687. * @param vector defines the vector to transform
  2688. * @param transformation defines the matrix to apply
  2689. * @param result defines the target vector
  2690. */
  2691. Vector2.TransformToRef = function (vector, transformation, result) {
  2692. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2693. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2694. result.x = x;
  2695. result.y = y;
  2696. };
  2697. /**
  2698. * Determines if a given vector is included in a triangle
  2699. * @param p defines the vector to test
  2700. * @param p0 defines 1st triangle point
  2701. * @param p1 defines 2nd triangle point
  2702. * @param p2 defines 3rd triangle point
  2703. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2704. */
  2705. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2706. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2707. var sign = a < 0 ? -1 : 1;
  2708. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2709. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2710. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2711. };
  2712. /**
  2713. * Gets the distance between the vectors "value1" and "value2"
  2714. * @param value1 defines first vector
  2715. * @param value2 defines second vector
  2716. * @returns the distance between vectors
  2717. */
  2718. Vector2.Distance = function (value1, value2) {
  2719. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2720. };
  2721. /**
  2722. * Returns the squared distance between the vectors "value1" and "value2"
  2723. * @param value1 defines first vector
  2724. * @param value2 defines second vector
  2725. * @returns the squared distance between vectors
  2726. */
  2727. Vector2.DistanceSquared = function (value1, value2) {
  2728. var x = value1.x - value2.x;
  2729. var y = value1.y - value2.y;
  2730. return (x * x) + (y * y);
  2731. };
  2732. /**
  2733. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2734. * @param value1 defines first vector
  2735. * @param value2 defines second vector
  2736. * @returns a new Vector2
  2737. */
  2738. Vector2.Center = function (value1, value2) {
  2739. var center = value1.add(value2);
  2740. center.scaleInPlace(0.5);
  2741. return center;
  2742. };
  2743. /**
  2744. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2745. * @param p defines the middle point
  2746. * @param segA defines one point of the segment
  2747. * @param segB defines the other point of the segment
  2748. * @returns the shortest distance
  2749. */
  2750. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2751. var l2 = Vector2.DistanceSquared(segA, segB);
  2752. if (l2 === 0.0) {
  2753. return Vector2.Distance(p, segA);
  2754. }
  2755. var v = segB.subtract(segA);
  2756. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2757. var proj = segA.add(v.multiplyByFloats(t, t));
  2758. return Vector2.Distance(p, proj);
  2759. };
  2760. return Vector2;
  2761. }());
  2762. BABYLON.Vector2 = Vector2;
  2763. /**
  2764. * Classed used to store (x,y,z) vector representation
  2765. * A Vector3 is the main object used in 3D geometry
  2766. * It can represent etiher the coordinates of a point the space, either a direction
  2767. * Reminder: Babylon.js uses a left handed forward facing system
  2768. */
  2769. var Vector3 = /** @class */ (function () {
  2770. /**
  2771. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2772. * @param x defines the first coordinates (on X axis)
  2773. * @param y defines the second coordinates (on Y axis)
  2774. * @param z defines the third coordinates (on Z axis)
  2775. */
  2776. function Vector3(
  2777. /**
  2778. * Defines the first coordinates (on X axis)
  2779. */
  2780. x,
  2781. /**
  2782. * Defines the second coordinates (on Y axis)
  2783. */
  2784. y,
  2785. /**
  2786. * Defines the third coordinates (on Z axis)
  2787. */
  2788. z) {
  2789. this.x = x;
  2790. this.y = y;
  2791. this.z = z;
  2792. }
  2793. /**
  2794. * Creates a string representation of the Vector3
  2795. * @returns a string with the Vector3 coordinates.
  2796. */
  2797. Vector3.prototype.toString = function () {
  2798. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2799. };
  2800. /**
  2801. * Gets the class name
  2802. * @returns the string "Vector3"
  2803. */
  2804. Vector3.prototype.getClassName = function () {
  2805. return "Vector3";
  2806. };
  2807. /**
  2808. * Creates the Vector3 hash code
  2809. * @returns a number which tends to be unique between Vector3 instances
  2810. */
  2811. Vector3.prototype.getHashCode = function () {
  2812. var hash = this.x || 0;
  2813. hash = (hash * 397) ^ (this.y || 0);
  2814. hash = (hash * 397) ^ (this.z || 0);
  2815. return hash;
  2816. };
  2817. // Operators
  2818. /**
  2819. * Creates an array containing three elements : the coordinates of the Vector3
  2820. * @returns a new array of numbers
  2821. */
  2822. Vector3.prototype.asArray = function () {
  2823. var result = [];
  2824. this.toArray(result, 0);
  2825. return result;
  2826. };
  2827. /**
  2828. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2829. * @param array defines the destination array
  2830. * @param index defines the offset in the destination array
  2831. * @returns the current Vector3
  2832. */
  2833. Vector3.prototype.toArray = function (array, index) {
  2834. if (index === void 0) { index = 0; }
  2835. array[index] = this.x;
  2836. array[index + 1] = this.y;
  2837. array[index + 2] = this.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2842. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2843. */
  2844. Vector3.prototype.toQuaternion = function () {
  2845. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2846. };
  2847. /**
  2848. * Adds the given vector to the current Vector3
  2849. * @param otherVector defines the second operand
  2850. * @returns the current updated Vector3
  2851. */
  2852. Vector3.prototype.addInPlace = function (otherVector) {
  2853. this.x += otherVector.x;
  2854. this.y += otherVector.y;
  2855. this.z += otherVector.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2860. * @param otherVector defines the second operand
  2861. * @returns the resulting Vector3
  2862. */
  2863. Vector3.prototype.add = function (otherVector) {
  2864. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2865. };
  2866. /**
  2867. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2868. * @param otherVector defines the second operand
  2869. * @param result defines the Vector3 object where to store the result
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.addToRef = function (otherVector, result) {
  2873. result.x = this.x + otherVector.x;
  2874. result.y = this.y + otherVector.y;
  2875. result.z = this.z + otherVector.z;
  2876. return this;
  2877. };
  2878. /**
  2879. * Subtract the given vector from the current Vector3
  2880. * @param otherVector defines the second operand
  2881. * @returns the current updated Vector3
  2882. */
  2883. Vector3.prototype.subtractInPlace = function (otherVector) {
  2884. this.x -= otherVector.x;
  2885. this.y -= otherVector.y;
  2886. this.z -= otherVector.z;
  2887. return this;
  2888. };
  2889. /**
  2890. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2891. * @param otherVector defines the second operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtract = function (otherVector) {
  2895. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2896. };
  2897. /**
  2898. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2899. * @param otherVector defines the second operand
  2900. * @param result defines the Vector3 object where to store the result
  2901. * @returns the current Vector3
  2902. */
  2903. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2904. result.x = this.x - otherVector.x;
  2905. result.y = this.y - otherVector.y;
  2906. result.z = this.z - otherVector.z;
  2907. return this;
  2908. };
  2909. /**
  2910. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2911. * @param x defines the x coordinate of the operand
  2912. * @param y defines the y coordinate of the operand
  2913. * @param z defines the z coordinate of the operand
  2914. * @returns the resulting Vector3
  2915. */
  2916. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2917. return new Vector3(this.x - x, this.y - y, this.z - z);
  2918. };
  2919. /**
  2920. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2921. * @param x defines the x coordinate of the operand
  2922. * @param y defines the y coordinate of the operand
  2923. * @param z defines the z coordinate of the operand
  2924. * @param result defines the Vector3 object where to store the result
  2925. * @returns the current Vector3
  2926. */
  2927. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2928. result.x = this.x - x;
  2929. result.y = this.y - y;
  2930. result.z = this.z - z;
  2931. return this;
  2932. };
  2933. /**
  2934. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2935. * @returns a new Vector3
  2936. */
  2937. Vector3.prototype.negate = function () {
  2938. return new Vector3(-this.x, -this.y, -this.z);
  2939. };
  2940. /**
  2941. * Multiplies the Vector3 coordinates by the float "scale"
  2942. * @param scale defines the multiplier factor
  2943. * @returns the current updated Vector3
  2944. */
  2945. Vector3.prototype.scaleInPlace = function (scale) {
  2946. this.x *= scale;
  2947. this.y *= scale;
  2948. this.z *= scale;
  2949. return this;
  2950. };
  2951. /**
  2952. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2953. * @param scale defines the multiplier factor
  2954. * @returns a new Vector3
  2955. */
  2956. Vector3.prototype.scale = function (scale) {
  2957. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2958. };
  2959. /**
  2960. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2961. * @param scale defines the multiplier factor
  2962. * @param result defines the Vector3 object where to store the result
  2963. * @returns the current Vector3
  2964. */
  2965. Vector3.prototype.scaleToRef = function (scale, result) {
  2966. result.x = this.x * scale;
  2967. result.y = this.y * scale;
  2968. result.z = this.z * scale;
  2969. return this;
  2970. };
  2971. /**
  2972. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2973. * @param scale defines the scale factor
  2974. * @param result defines the Vector3 object where to store the result
  2975. * @returns the unmodified current Vector3
  2976. */
  2977. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2978. result.x += this.x * scale;
  2979. result.y += this.y * scale;
  2980. result.z += this.z * scale;
  2981. return this;
  2982. };
  2983. /**
  2984. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2985. * @param otherVector defines the second operand
  2986. * @returns true if both vectors are equals
  2987. */
  2988. Vector3.prototype.equals = function (otherVector) {
  2989. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2990. };
  2991. /**
  2992. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2993. * @param otherVector defines the second operand
  2994. * @param epsilon defines the minimal distance to define values as equals
  2995. * @returns true if both vectors are distant less than epsilon
  2996. */
  2997. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2998. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2999. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3000. };
  3001. /**
  3002. * Returns true if the current Vector3 coordinates equals the given floats
  3003. * @param x defines the x coordinate of the operand
  3004. * @param y defines the y coordinate of the operand
  3005. * @param z defines the z coordinate of the operand
  3006. * @returns true if both vectors are equals
  3007. */
  3008. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3009. return this.x === x && this.y === y && this.z === z;
  3010. };
  3011. /**
  3012. * Multiplies the current Vector3 coordinates by the given ones
  3013. * @param otherVector defines the second operand
  3014. * @returns the current updated Vector3
  3015. */
  3016. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3017. this.x *= otherVector.x;
  3018. this.y *= otherVector.y;
  3019. this.z *= otherVector.z;
  3020. return this;
  3021. };
  3022. /**
  3023. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3024. * @param otherVector defines the second operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiply = function (otherVector) {
  3028. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3029. };
  3030. /**
  3031. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3032. * @param otherVector defines the second operand
  3033. * @param result defines the Vector3 object where to store the result
  3034. * @returns the current Vector3
  3035. */
  3036. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3037. result.x = this.x * otherVector.x;
  3038. result.y = this.y * otherVector.y;
  3039. result.z = this.z * otherVector.z;
  3040. return this;
  3041. };
  3042. /**
  3043. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3044. * @param x defines the x coordinate of the operand
  3045. * @param y defines the y coordinate of the operand
  3046. * @param z defines the z coordinate of the operand
  3047. * @returns the new Vector3
  3048. */
  3049. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3050. return new Vector3(this.x * x, this.y * y, this.z * z);
  3051. };
  3052. /**
  3053. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3054. * @param otherVector defines the second operand
  3055. * @returns the new Vector3
  3056. */
  3057. Vector3.prototype.divide = function (otherVector) {
  3058. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3059. };
  3060. /**
  3061. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3062. * @param otherVector defines the second operand
  3063. * @param result defines the Vector3 object where to store the result
  3064. * @returns the current Vector3
  3065. */
  3066. Vector3.prototype.divideToRef = function (otherVector, result) {
  3067. result.x = this.x / otherVector.x;
  3068. result.y = this.y / otherVector.y;
  3069. result.z = this.z / otherVector.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Divides the current Vector3 coordinates by the given ones.
  3074. * @param otherVector defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.divideInPlace = function (otherVector) {
  3078. return this.divideToRef(otherVector, this);
  3079. };
  3080. /**
  3081. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3082. * @param other defines the second operand
  3083. * @returns the current updated Vector3
  3084. */
  3085. Vector3.prototype.minimizeInPlace = function (other) {
  3086. if (other.x < this.x)
  3087. this.x = other.x;
  3088. if (other.y < this.y)
  3089. this.y = other.y;
  3090. if (other.z < this.z)
  3091. this.z = other.z;
  3092. return this;
  3093. };
  3094. /**
  3095. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3096. * @param other defines the second operand
  3097. * @returns the current updated Vector3
  3098. */
  3099. Vector3.prototype.maximizeInPlace = function (other) {
  3100. if (other.x > this.x)
  3101. this.x = other.x;
  3102. if (other.y > this.y)
  3103. this.y = other.y;
  3104. if (other.z > this.z)
  3105. this.z = other.z;
  3106. return this;
  3107. };
  3108. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3109. /**
  3110. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3111. */
  3112. get: function () {
  3113. var absX = Math.abs(this.x);
  3114. var absY = Math.abs(this.y);
  3115. if (absX !== absY) {
  3116. return true;
  3117. }
  3118. var absZ = Math.abs(this.z);
  3119. if (absX !== absZ) {
  3120. return true;
  3121. }
  3122. if (absY !== absZ) {
  3123. return true;
  3124. }
  3125. return false;
  3126. },
  3127. enumerable: true,
  3128. configurable: true
  3129. });
  3130. // Properties
  3131. /**
  3132. * Gets the length of the Vector3
  3133. * @returns the length of the Vecto3
  3134. */
  3135. Vector3.prototype.length = function () {
  3136. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3137. };
  3138. /**
  3139. * Gets the squared length of the Vector3
  3140. * @returns squared length of the Vector3
  3141. */
  3142. Vector3.prototype.lengthSquared = function () {
  3143. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3144. };
  3145. /**
  3146. * Normalize the current Vector3.
  3147. * Please note that this is an in place operation.
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.normalize = function () {
  3151. var len = this.length();
  3152. if (len === 0 || len === 1.0)
  3153. return this;
  3154. var num = 1.0 / len;
  3155. this.x *= num;
  3156. this.y *= num;
  3157. this.z *= num;
  3158. return this;
  3159. };
  3160. /**
  3161. * Normalize the current Vector3 to a new vector
  3162. * @returns the new Vector3
  3163. */
  3164. Vector3.prototype.normalizeToNew = function () {
  3165. var normalized = new Vector3(0, 0, 0);
  3166. this.normalizeToRef(normalized);
  3167. return normalized;
  3168. };
  3169. /**
  3170. * Normalize the current Vector3 to the reference
  3171. * @param reference define the Vector3 to update
  3172. * @returns the updated Vector3
  3173. */
  3174. Vector3.prototype.normalizeToRef = function (reference) {
  3175. var len = this.length();
  3176. if (len === 0 || len === 1.0) {
  3177. reference.set(this.x, this.y, this.z);
  3178. return reference;
  3179. }
  3180. var scale = 1.0 / len;
  3181. this.scaleToRef(scale, reference);
  3182. return reference;
  3183. };
  3184. /**
  3185. * Creates a new Vector3 copied from the current Vector3
  3186. * @returns the new Vector3
  3187. */
  3188. Vector3.prototype.clone = function () {
  3189. return new Vector3(this.x, this.y, this.z);
  3190. };
  3191. /**
  3192. * Copies the given vector coordinates to the current Vector3 ones
  3193. * @param source defines the source Vector3
  3194. * @returns the current updated Vector3
  3195. */
  3196. Vector3.prototype.copyFrom = function (source) {
  3197. this.x = source.x;
  3198. this.y = source.y;
  3199. this.z = source.z;
  3200. return this;
  3201. };
  3202. /**
  3203. * Copies the given floats to the current Vector3 coordinates
  3204. * @param x defines the x coordinate of the operand
  3205. * @param y defines the y coordinate of the operand
  3206. * @param z defines the z coordinate of the operand
  3207. * @returns the current updated Vector3
  3208. */
  3209. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3210. this.x = x;
  3211. this.y = y;
  3212. this.z = z;
  3213. return this;
  3214. };
  3215. /**
  3216. * Copies the given floats to the current Vector3 coordinates
  3217. * @param x defines the x coordinate of the operand
  3218. * @param y defines the y coordinate of the operand
  3219. * @param z defines the z coordinate of the operand
  3220. * @returns the current updated Vector3
  3221. */
  3222. Vector3.prototype.set = function (x, y, z) {
  3223. return this.copyFromFloats(x, y, z);
  3224. };
  3225. // Statics
  3226. /**
  3227. * Get the clip factor between two vectors
  3228. * @param vector0 defines the first operand
  3229. * @param vector1 defines the second operand
  3230. * @param axis defines the axis to use
  3231. * @param size defines the size along the axis
  3232. * @returns the clip factor
  3233. */
  3234. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3235. var d0 = Vector3.Dot(vector0, axis) - size;
  3236. var d1 = Vector3.Dot(vector1, axis) - size;
  3237. var s = d0 / (d0 - d1);
  3238. return s;
  3239. };
  3240. /**
  3241. * Get angle between two vectors
  3242. * @param vector0 angle between vector0 and vector1
  3243. * @param vector1 angle between vector0 and vector1
  3244. * @param normal direction of the normal
  3245. * @return the angle between vector0 and vector1
  3246. */
  3247. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3248. var v0 = vector0.clone().normalize();
  3249. var v1 = vector1.clone().normalize();
  3250. var dot = Vector3.Dot(v0, v1);
  3251. var n = Vector3.Cross(v0, v1);
  3252. if (Vector3.Dot(n, normal) > 0) {
  3253. return Math.acos(dot);
  3254. }
  3255. return -Math.acos(dot);
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @returns the new Vector3
  3262. */
  3263. Vector3.FromArray = function (array, offset) {
  3264. if (!offset) {
  3265. offset = 0;
  3266. }
  3267. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3268. };
  3269. /**
  3270. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3271. * This function is deprecated. Use FromArray instead
  3272. * @param array defines the source array
  3273. * @param offset defines the offset in the source array
  3274. * @returns the new Vector3
  3275. */
  3276. Vector3.FromFloatArray = function (array, offset) {
  3277. return Vector3.FromArray(array, offset);
  3278. };
  3279. /**
  3280. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3281. * @param array defines the source array
  3282. * @param offset defines the offset in the source array
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromArrayToRef = function (array, offset, result) {
  3286. result.x = array[offset];
  3287. result.y = array[offset + 1];
  3288. result.z = array[offset + 2];
  3289. };
  3290. /**
  3291. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3292. * This function is deprecated. Use FromArrayToRef instead.
  3293. * @param array defines the source array
  3294. * @param offset defines the offset in the source array
  3295. * @param result defines the Vector3 where to store the result
  3296. */
  3297. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3298. return Vector3.FromArrayToRef(array, offset, result);
  3299. };
  3300. /**
  3301. * Sets the given vector "result" with the given floats.
  3302. * @param x defines the x coordinate of the source
  3303. * @param y defines the y coordinate of the source
  3304. * @param z defines the z coordinate of the source
  3305. * @param result defines the Vector3 where to store the result
  3306. */
  3307. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3308. result.x = x;
  3309. result.y = y;
  3310. result.z = z;
  3311. };
  3312. /**
  3313. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3314. * @returns a new empty Vector3
  3315. */
  3316. Vector3.Zero = function () {
  3317. return new Vector3(0.0, 0.0, 0.0);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3321. * @returns a new unit Vector3
  3322. */
  3323. Vector3.One = function () {
  3324. return new Vector3(1.0, 1.0, 1.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3328. * @returns a new up Vector3
  3329. */
  3330. Vector3.Up = function () {
  3331. return new Vector3(0.0, 1.0, 0.0);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3335. * @returns a new forward Vector3
  3336. */
  3337. Vector3.Forward = function () {
  3338. return new Vector3(0.0, 0.0, 1.0);
  3339. };
  3340. /**
  3341. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3342. * @returns a new right Vector3
  3343. */
  3344. Vector3.Right = function () {
  3345. return new Vector3(1.0, 0.0, 0.0);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3349. * @returns a new left Vector3
  3350. */
  3351. Vector3.Left = function () {
  3352. return new Vector3(-1.0, 0.0, 0.0);
  3353. };
  3354. /**
  3355. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3356. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3357. * @param vector defines the Vector3 to transform
  3358. * @param transformation defines the transformation matrix
  3359. * @returns the transformed Vector3
  3360. */
  3361. Vector3.TransformCoordinates = function (vector, transformation) {
  3362. var result = Vector3.Zero();
  3363. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3364. return result;
  3365. };
  3366. /**
  3367. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3368. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @param result defines the Vector3 where to store the result
  3372. */
  3373. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3374. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3375. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3376. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3377. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3378. result.x = x / w;
  3379. result.y = y / w;
  3380. result.z = z / w;
  3381. };
  3382. /**
  3383. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3384. * This method computes tranformed coordinates only, not transformed direction vectors
  3385. * @param x define the x coordinate of the source vector
  3386. * @param y define the y coordinate of the source vector
  3387. * @param z define the z coordinate of the source vector
  3388. * @param transformation defines the transformation matrix
  3389. * @param result defines the Vector3 where to store the result
  3390. */
  3391. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3392. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3393. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3394. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3395. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3396. result.x = rx / rw;
  3397. result.y = ry / rw;
  3398. result.z = rz / rw;
  3399. };
  3400. /**
  3401. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3402. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3403. * @param vector defines the Vector3 to transform
  3404. * @param transformation defines the transformation matrix
  3405. * @returns the new Vector3
  3406. */
  3407. Vector3.TransformNormal = function (vector, transformation) {
  3408. var result = Vector3.Zero();
  3409. Vector3.TransformNormalToRef(vector, transformation, result);
  3410. return result;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param vector defines the Vector3 to transform
  3416. * @param transformation defines the transformation matrix
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3420. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3421. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3422. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3423. result.x = x;
  3424. result.y = y;
  3425. result.z = z;
  3426. };
  3427. /**
  3428. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3429. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3430. * @param x define the x coordinate of the source vector
  3431. * @param y define the y coordinate of the source vector
  3432. * @param z define the z coordinate of the source vector
  3433. * @param transformation defines the transformation matrix
  3434. * @param result defines the Vector3 where to store the result
  3435. */
  3436. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3437. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3438. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3439. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3443. * @param value1 defines the first control point
  3444. * @param value2 defines the second control point
  3445. * @param value3 defines the third control point
  3446. * @param value4 defines the fourth control point
  3447. * @param amount defines the amount on the spline to use
  3448. * @returns the new Vector3
  3449. */
  3450. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3451. var squared = amount * amount;
  3452. var cubed = amount * squared;
  3453. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3454. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3455. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3456. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3457. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3458. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3459. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3460. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3461. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3462. return new Vector3(x, y, z);
  3463. };
  3464. /**
  3465. * 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"
  3466. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3467. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3468. * @param value defines the current value
  3469. * @param min defines the lower range value
  3470. * @param max defines the upper range value
  3471. * @returns the new Vector3
  3472. */
  3473. Vector3.Clamp = function (value, min, max) {
  3474. var x = value.x;
  3475. x = (x > max.x) ? max.x : x;
  3476. x = (x < min.x) ? min.x : x;
  3477. var y = value.y;
  3478. y = (y > max.y) ? max.y : y;
  3479. y = (y < min.y) ? min.y : y;
  3480. var z = value.z;
  3481. z = (z > max.z) ? max.z : z;
  3482. z = (z < min.z) ? min.z : z;
  3483. return new Vector3(x, y, z);
  3484. };
  3485. /**
  3486. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3487. * @param value1 defines the first control point
  3488. * @param tangent1 defines the first tangent vector
  3489. * @param value2 defines the second control point
  3490. * @param tangent2 defines the second tangent vector
  3491. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3492. * @returns the new Vector3
  3493. */
  3494. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3495. var squared = amount * amount;
  3496. var cubed = amount * squared;
  3497. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3498. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3499. var part3 = (cubed - (2.0 * squared)) + amount;
  3500. var part4 = cubed - squared;
  3501. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3502. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3503. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3504. return new Vector3(x, y, z);
  3505. };
  3506. /**
  3507. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3508. * @param start defines the start value
  3509. * @param end defines the end value
  3510. * @param amount max defines amount between both (between 0 and 1)
  3511. * @returns the new Vector3
  3512. */
  3513. Vector3.Lerp = function (start, end, amount) {
  3514. var result = new Vector3(0, 0, 0);
  3515. Vector3.LerpToRef(start, end, amount, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3520. * @param start defines the start value
  3521. * @param end defines the end value
  3522. * @param amount max defines amount between both (between 0 and 1)
  3523. * @param result defines the Vector3 where to store the result
  3524. */
  3525. Vector3.LerpToRef = function (start, end, amount, result) {
  3526. result.x = start.x + ((end.x - start.x) * amount);
  3527. result.y = start.y + ((end.y - start.y) * amount);
  3528. result.z = start.z + ((end.z - start.z) * amount);
  3529. };
  3530. /**
  3531. * Returns the dot product (float) between the vectors "left" and "right"
  3532. * @param left defines the left operand
  3533. * @param right defines the right operand
  3534. * @returns the dot product
  3535. */
  3536. Vector3.Dot = function (left, right) {
  3537. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3538. };
  3539. /**
  3540. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3541. * The cross product is then orthogonal to both "left" and "right"
  3542. * @param left defines the left operand
  3543. * @param right defines the right operand
  3544. * @returns the cross product
  3545. */
  3546. Vector3.Cross = function (left, right) {
  3547. var result = Vector3.Zero();
  3548. Vector3.CrossToRef(left, right, result);
  3549. return result;
  3550. };
  3551. /**
  3552. * Sets the given vector "result" with the cross product of "left" and "right"
  3553. * The cross product is then orthogonal to both "left" and "right"
  3554. * @param left defines the left operand
  3555. * @param right defines the right operand
  3556. * @param result defines the Vector3 where to store the result
  3557. */
  3558. Vector3.CrossToRef = function (left, right, result) {
  3559. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3560. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3561. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3562. result.copyFrom(MathTmp.Vector3[0]);
  3563. };
  3564. /**
  3565. * Returns a new Vector3 as the normalization of the given vector
  3566. * @param vector defines the Vector3 to normalize
  3567. * @returns the new Vector3
  3568. */
  3569. Vector3.Normalize = function (vector) {
  3570. var result = Vector3.Zero();
  3571. Vector3.NormalizeToRef(vector, result);
  3572. return result;
  3573. };
  3574. /**
  3575. * Sets the given vector "result" with the normalization of the given first vector
  3576. * @param vector defines the Vector3 to normalize
  3577. * @param result defines the Vector3 where to store the result
  3578. */
  3579. Vector3.NormalizeToRef = function (vector, result) {
  3580. result.copyFrom(vector);
  3581. result.normalize();
  3582. };
  3583. /**
  3584. * Project a Vector3 onto screen space
  3585. * @param vector defines the Vector3 to project
  3586. * @param world defines the world matrix to use
  3587. * @param transform defines the transform (view x projection) matrix to use
  3588. * @param viewport defines the screen viewport to use
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Project = function (vector, world, transform, viewport) {
  3592. var cw = viewport.width;
  3593. var ch = viewport.height;
  3594. var cx = viewport.x;
  3595. var cy = viewport.y;
  3596. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3597. 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);
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.multiplyToRef(viewportMatrix, matrix);
  3601. return Vector3.TransformCoordinates(vector, matrix);
  3602. };
  3603. /**
  3604. * Unproject from screen space to object space
  3605. * @param source defines the screen space Vector3 to use
  3606. * @param viewportWidth defines the current width of the viewport
  3607. * @param viewportHeight defines the current height of the viewport
  3608. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3609. * @param transform defines the transform (view x projection) matrix to use
  3610. * @returns the new Vector3
  3611. */
  3612. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3613. var matrix = MathTmp.Matrix[0];
  3614. world.multiplyToRef(transform, matrix);
  3615. matrix.invert();
  3616. source.x = source.x / viewportWidth * 2 - 1;
  3617. source.y = -(source.y / viewportHeight * 2 - 1);
  3618. var vector = Vector3.TransformCoordinates(source, matrix);
  3619. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3620. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3621. vector = vector.scale(1.0 / num);
  3622. }
  3623. return vector;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3636. var result = Vector3.Zero();
  3637. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Unproject from screen space to object space
  3642. * @param source defines the screen space Vector3 to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3652. };
  3653. /**
  3654. * Unproject from screen space to object space
  3655. * @param sourceX defines the screen space x coordinate to use
  3656. * @param sourceY defines the screen space y coordinate to use
  3657. * @param sourceZ defines the screen space z coordinate to use
  3658. * @param viewportWidth defines the current width of the viewport
  3659. * @param viewportHeight defines the current height of the viewport
  3660. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3661. * @param view defines the view matrix to use
  3662. * @param projection defines the projection matrix to use
  3663. * @param result defines the Vector3 where to store the result
  3664. */
  3665. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3666. var matrix = MathTmp.Matrix[0];
  3667. world.multiplyToRef(view, matrix);
  3668. matrix.multiplyToRef(projection, matrix);
  3669. matrix.invert();
  3670. var screenSource = MathTmp.Vector3[0];
  3671. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3672. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3673. screenSource.z = 2 * sourceZ - 1.0;
  3674. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3675. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3676. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3677. result.scaleInPlace(1.0 / num);
  3678. }
  3679. };
  3680. /**
  3681. * Gets the minimal coordinate values between two Vector3
  3682. * @param left defines the first operand
  3683. * @param right defines the second operand
  3684. * @returns the new Vector3
  3685. */
  3686. Vector3.Minimize = function (left, right) {
  3687. var min = left.clone();
  3688. min.minimizeInPlace(right);
  3689. return min;
  3690. };
  3691. /**
  3692. * Gets the maximal coordinate values between two Vector3
  3693. * @param left defines the first operand
  3694. * @param right defines the second operand
  3695. * @returns the new Vector3
  3696. */
  3697. Vector3.Maximize = function (left, right) {
  3698. var max = left.clone();
  3699. max.maximizeInPlace(right);
  3700. return max;
  3701. };
  3702. /**
  3703. * Returns the distance between the vectors "value1" and "value2"
  3704. * @param value1 defines the first operand
  3705. * @param value2 defines the second operand
  3706. * @returns the distance
  3707. */
  3708. Vector3.Distance = function (value1, value2) {
  3709. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3710. };
  3711. /**
  3712. * Returns the squared distance between the vectors "value1" and "value2"
  3713. * @param value1 defines the first operand
  3714. * @param value2 defines the second operand
  3715. * @returns the squared distance
  3716. */
  3717. Vector3.DistanceSquared = function (value1, value2) {
  3718. var x = value1.x - value2.x;
  3719. var y = value1.y - value2.y;
  3720. var z = value1.z - value2.z;
  3721. return (x * x) + (y * y) + (z * z);
  3722. };
  3723. /**
  3724. * Returns a new Vector3 located at the center between "value1" and "value2"
  3725. * @param value1 defines the first operand
  3726. * @param value2 defines the second operand
  3727. * @returns the new Vector3
  3728. */
  3729. Vector3.Center = function (value1, value2) {
  3730. var center = value1.add(value2);
  3731. center.scaleInPlace(0.5);
  3732. return center;
  3733. };
  3734. /**
  3735. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3736. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3737. * to something in order to rotate it from its local system to the given target system
  3738. * Note: axis1, axis2 and axis3 are normalized during this operation
  3739. * @param axis1 defines the first axis
  3740. * @param axis2 defines the second axis
  3741. * @param axis3 defines the third axis
  3742. * @returns a new Vector3
  3743. */
  3744. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3745. var rotation = Vector3.Zero();
  3746. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3747. return rotation;
  3748. };
  3749. /**
  3750. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3751. * @param axis1 defines the first axis
  3752. * @param axis2 defines the second axis
  3753. * @param axis3 defines the third axis
  3754. * @param ref defines the Vector3 where to store the result
  3755. */
  3756. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3757. var quat = MathTmp.Quaternion[0];
  3758. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3759. quat.toEulerAnglesToRef(ref);
  3760. };
  3761. return Vector3;
  3762. }());
  3763. BABYLON.Vector3 = Vector3;
  3764. //Vector4 class created for EulerAngle class conversion to Quaternion
  3765. var Vector4 = /** @class */ (function () {
  3766. /**
  3767. * Creates a Vector4 object from the given floats.
  3768. */
  3769. function Vector4(x, y, z, w) {
  3770. this.x = x;
  3771. this.y = y;
  3772. this.z = z;
  3773. this.w = w;
  3774. }
  3775. /**
  3776. * Returns the string with the Vector4 coordinates.
  3777. */
  3778. Vector4.prototype.toString = function () {
  3779. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3780. };
  3781. /**
  3782. * Returns the string "Vector4".
  3783. */
  3784. Vector4.prototype.getClassName = function () {
  3785. return "Vector4";
  3786. };
  3787. /**
  3788. * Returns the Vector4 hash code.
  3789. */
  3790. Vector4.prototype.getHashCode = function () {
  3791. var hash = this.x || 0;
  3792. hash = (hash * 397) ^ (this.y || 0);
  3793. hash = (hash * 397) ^ (this.z || 0);
  3794. hash = (hash * 397) ^ (this.w || 0);
  3795. return hash;
  3796. };
  3797. // Operators
  3798. /**
  3799. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3800. */
  3801. Vector4.prototype.asArray = function () {
  3802. var result = new Array();
  3803. this.toArray(result, 0);
  3804. return result;
  3805. };
  3806. /**
  3807. * Populates the given array from the given index with the Vector4 coordinates.
  3808. * Returns the Vector4.
  3809. */
  3810. Vector4.prototype.toArray = function (array, index) {
  3811. if (index === undefined) {
  3812. index = 0;
  3813. }
  3814. array[index] = this.x;
  3815. array[index + 1] = this.y;
  3816. array[index + 2] = this.z;
  3817. array[index + 3] = this.w;
  3818. return this;
  3819. };
  3820. /**
  3821. * Adds the given vector to the current Vector4.
  3822. * Returns the updated Vector4.
  3823. */
  3824. Vector4.prototype.addInPlace = function (otherVector) {
  3825. this.x += otherVector.x;
  3826. this.y += otherVector.y;
  3827. this.z += otherVector.z;
  3828. this.w += otherVector.w;
  3829. return this;
  3830. };
  3831. /**
  3832. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3833. */
  3834. Vector4.prototype.add = function (otherVector) {
  3835. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3836. };
  3837. /**
  3838. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3839. * Returns the current Vector4.
  3840. */
  3841. Vector4.prototype.addToRef = function (otherVector, result) {
  3842. result.x = this.x + otherVector.x;
  3843. result.y = this.y + otherVector.y;
  3844. result.z = this.z + otherVector.z;
  3845. result.w = this.w + otherVector.w;
  3846. return this;
  3847. };
  3848. /**
  3849. * Subtract in place the given vector from the current Vector4.
  3850. * Returns the updated Vector4.
  3851. */
  3852. Vector4.prototype.subtractInPlace = function (otherVector) {
  3853. this.x -= otherVector.x;
  3854. this.y -= otherVector.y;
  3855. this.z -= otherVector.z;
  3856. this.w -= otherVector.w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3861. */
  3862. Vector4.prototype.subtract = function (otherVector) {
  3863. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3864. };
  3865. /**
  3866. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3870. result.x = this.x - otherVector.x;
  3871. result.y = this.y - otherVector.y;
  3872. result.z = this.z - otherVector.z;
  3873. result.w = this.w - otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3878. */
  3879. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3880. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3881. };
  3882. /**
  3883. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3884. * Returns the current Vector4.
  3885. */
  3886. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3887. result.x = this.x - x;
  3888. result.y = this.y - y;
  3889. result.z = this.z - z;
  3890. result.w = this.w - w;
  3891. return this;
  3892. };
  3893. /**
  3894. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3895. */
  3896. Vector4.prototype.negate = function () {
  3897. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3898. };
  3899. /**
  3900. * Multiplies the current Vector4 coordinates by scale (float).
  3901. * Returns the updated Vector4.
  3902. */
  3903. Vector4.prototype.scaleInPlace = function (scale) {
  3904. this.x *= scale;
  3905. this.y *= scale;
  3906. this.z *= scale;
  3907. this.w *= scale;
  3908. return this;
  3909. };
  3910. /**
  3911. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3912. */
  3913. Vector4.prototype.scale = function (scale) {
  3914. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3915. };
  3916. /**
  3917. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3918. * Returns the current Vector4.
  3919. */
  3920. Vector4.prototype.scaleToRef = function (scale, result) {
  3921. result.x = this.x * scale;
  3922. result.y = this.y * scale;
  3923. result.z = this.z * scale;
  3924. result.w = this.w * scale;
  3925. return this;
  3926. };
  3927. /**
  3928. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3929. * @param scale defines the scale factor
  3930. * @param result defines the Vector4 object where to store the result
  3931. * @returns the unmodified current Vector4
  3932. */
  3933. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3934. result.x += this.x * scale;
  3935. result.y += this.y * scale;
  3936. result.z += this.z * scale;
  3937. result.w += this.w * scale;
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3942. */
  3943. Vector4.prototype.equals = function (otherVector) {
  3944. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3945. };
  3946. /**
  3947. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3948. */
  3949. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3950. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3951. return otherVector
  3952. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3953. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3954. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3955. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3956. };
  3957. /**
  3958. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3959. */
  3960. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3961. return this.x === x && this.y === y && this.z === z && this.w === w;
  3962. };
  3963. /**
  3964. * Multiplies in place the current Vector4 by the given one.
  3965. * Returns the updated Vector4.
  3966. */
  3967. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3968. this.x *= otherVector.x;
  3969. this.y *= otherVector.y;
  3970. this.z *= otherVector.z;
  3971. this.w *= otherVector.w;
  3972. return this;
  3973. };
  3974. /**
  3975. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3976. */
  3977. Vector4.prototype.multiply = function (otherVector) {
  3978. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3979. };
  3980. /**
  3981. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3982. * Returns the current Vector4.
  3983. */
  3984. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3985. result.x = this.x * otherVector.x;
  3986. result.y = this.y * otherVector.y;
  3987. result.z = this.z * otherVector.z;
  3988. result.w = this.w * otherVector.w;
  3989. return this;
  3990. };
  3991. /**
  3992. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3993. */
  3994. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3995. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3996. };
  3997. /**
  3998. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3999. */
  4000. Vector4.prototype.divide = function (otherVector) {
  4001. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4002. };
  4003. /**
  4004. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4005. * Returns the current Vector4.
  4006. */
  4007. Vector4.prototype.divideToRef = function (otherVector, result) {
  4008. result.x = this.x / otherVector.x;
  4009. result.y = this.y / otherVector.y;
  4010. result.z = this.z / otherVector.z;
  4011. result.w = this.w / otherVector.w;
  4012. return this;
  4013. };
  4014. /**
  4015. * Divides the current Vector3 coordinates by the given ones.
  4016. * @returns the updated Vector3.
  4017. */
  4018. Vector4.prototype.divideInPlace = function (otherVector) {
  4019. return this.divideToRef(otherVector, this);
  4020. };
  4021. /**
  4022. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4023. * @param other defines the second operand
  4024. * @returns the current updated Vector4
  4025. */
  4026. Vector4.prototype.minimizeInPlace = function (other) {
  4027. if (other.x < this.x)
  4028. this.x = other.x;
  4029. if (other.y < this.y)
  4030. this.y = other.y;
  4031. if (other.z < this.z)
  4032. this.z = other.z;
  4033. if (other.w < this.w)
  4034. this.w = other.w;
  4035. return this;
  4036. };
  4037. /**
  4038. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4039. * @param other defines the second operand
  4040. * @returns the current updated Vector4
  4041. */
  4042. Vector4.prototype.maximizeInPlace = function (other) {
  4043. if (other.x > this.x)
  4044. this.x = other.x;
  4045. if (other.y > this.y)
  4046. this.y = other.y;
  4047. if (other.z > this.z)
  4048. this.z = other.z;
  4049. if (other.w > this.w)
  4050. this.w = other.w;
  4051. return this;
  4052. };
  4053. // Properties
  4054. /**
  4055. * Returns the Vector4 length (float).
  4056. */
  4057. Vector4.prototype.length = function () {
  4058. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4059. };
  4060. /**
  4061. * Returns the Vector4 squared length (float).
  4062. */
  4063. Vector4.prototype.lengthSquared = function () {
  4064. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4065. };
  4066. // Methods
  4067. /**
  4068. * Normalizes in place the Vector4.
  4069. * Returns the updated Vector4.
  4070. */
  4071. Vector4.prototype.normalize = function () {
  4072. var len = this.length();
  4073. if (len === 0)
  4074. return this;
  4075. var num = 1.0 / len;
  4076. this.x *= num;
  4077. this.y *= num;
  4078. this.z *= num;
  4079. this.w *= num;
  4080. return this;
  4081. };
  4082. /**
  4083. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4084. */
  4085. Vector4.prototype.toVector3 = function () {
  4086. return new Vector3(this.x, this.y, this.z);
  4087. };
  4088. /**
  4089. * Returns a new Vector4 copied from the current one.
  4090. */
  4091. Vector4.prototype.clone = function () {
  4092. return new Vector4(this.x, this.y, this.z, this.w);
  4093. };
  4094. /**
  4095. * Updates the current Vector4 with the given one coordinates.
  4096. * Returns the updated Vector4.
  4097. */
  4098. Vector4.prototype.copyFrom = function (source) {
  4099. this.x = source.x;
  4100. this.y = source.y;
  4101. this.z = source.z;
  4102. this.w = source.w;
  4103. return this;
  4104. };
  4105. /**
  4106. * Updates the current Vector4 coordinates with the given floats.
  4107. * Returns the updated Vector4.
  4108. */
  4109. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4110. this.x = x;
  4111. this.y = y;
  4112. this.z = z;
  4113. this.w = w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Updates the current Vector4 coordinates with the given floats.
  4118. * Returns the updated Vector4.
  4119. */
  4120. Vector4.prototype.set = function (x, y, z, w) {
  4121. return this.copyFromFloats(x, y, z, w);
  4122. };
  4123. // Statics
  4124. /**
  4125. * Returns a new Vector4 set from the starting index of the given array.
  4126. */
  4127. Vector4.FromArray = function (array, offset) {
  4128. if (!offset) {
  4129. offset = 0;
  4130. }
  4131. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" from the starting index of the given array.
  4135. */
  4136. Vector4.FromArrayToRef = function (array, offset, result) {
  4137. result.x = array[offset];
  4138. result.y = array[offset + 1];
  4139. result.z = array[offset + 2];
  4140. result.w = array[offset + 3];
  4141. };
  4142. /**
  4143. * Updates the given vector "result" from the starting index of the given Float32Array.
  4144. */
  4145. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4146. Vector4.FromArrayToRef(array, offset, result);
  4147. };
  4148. /**
  4149. * Updates the given vector "result" coordinates from the given floats.
  4150. */
  4151. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4152. result.x = x;
  4153. result.y = y;
  4154. result.z = z;
  4155. result.w = w;
  4156. };
  4157. /**
  4158. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4159. */
  4160. Vector4.Zero = function () {
  4161. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4162. };
  4163. /**
  4164. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4165. */
  4166. Vector4.One = function () {
  4167. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4168. };
  4169. /**
  4170. * Returns a new normalized Vector4 from the given one.
  4171. */
  4172. Vector4.Normalize = function (vector) {
  4173. var result = Vector4.Zero();
  4174. Vector4.NormalizeToRef(vector, result);
  4175. return result;
  4176. };
  4177. /**
  4178. * Updates the given vector "result" from the normalization of the given one.
  4179. */
  4180. Vector4.NormalizeToRef = function (vector, result) {
  4181. result.copyFrom(vector);
  4182. result.normalize();
  4183. };
  4184. Vector4.Minimize = function (left, right) {
  4185. var min = left.clone();
  4186. min.minimizeInPlace(right);
  4187. return min;
  4188. };
  4189. Vector4.Maximize = function (left, right) {
  4190. var max = left.clone();
  4191. max.maximizeInPlace(right);
  4192. return max;
  4193. };
  4194. /**
  4195. * Returns the distance (float) between the vectors "value1" and "value2".
  4196. */
  4197. Vector4.Distance = function (value1, value2) {
  4198. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4199. };
  4200. /**
  4201. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4202. */
  4203. Vector4.DistanceSquared = function (value1, value2) {
  4204. var x = value1.x - value2.x;
  4205. var y = value1.y - value2.y;
  4206. var z = value1.z - value2.z;
  4207. var w = value1.w - value2.w;
  4208. return (x * x) + (y * y) + (z * z) + (w * w);
  4209. };
  4210. /**
  4211. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4212. */
  4213. Vector4.Center = function (value1, value2) {
  4214. var center = value1.add(value2);
  4215. center.scaleInPlace(0.5);
  4216. return center;
  4217. };
  4218. /**
  4219. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4220. * This methods computes transformed normalized direction vectors only.
  4221. */
  4222. Vector4.TransformNormal = function (vector, transformation) {
  4223. var result = Vector4.Zero();
  4224. Vector4.TransformNormalToRef(vector, transformation, result);
  4225. return result;
  4226. };
  4227. /**
  4228. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4229. * This methods computes transformed normalized direction vectors only.
  4230. */
  4231. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4232. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4233. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4234. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4235. result.x = x;
  4236. result.y = y;
  4237. result.z = z;
  4238. result.w = vector.w;
  4239. };
  4240. /**
  4241. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4242. * This methods computes transformed normalized direction vectors only.
  4243. */
  4244. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4245. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4246. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4247. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4248. result.w = w;
  4249. };
  4250. return Vector4;
  4251. }());
  4252. BABYLON.Vector4 = Vector4;
  4253. var Size = /** @class */ (function () {
  4254. /**
  4255. * Creates a Size object from the given width and height (floats).
  4256. */
  4257. function Size(width, height) {
  4258. this.width = width;
  4259. this.height = height;
  4260. }
  4261. // Returns a string with the Size width and height.
  4262. Size.prototype.toString = function () {
  4263. return "{W: " + this.width + ", H: " + this.height + "}";
  4264. };
  4265. /**
  4266. * Returns the string "Size"
  4267. */
  4268. Size.prototype.getClassName = function () {
  4269. return "Size";
  4270. };
  4271. /**
  4272. * Returns the Size hash code.
  4273. */
  4274. Size.prototype.getHashCode = function () {
  4275. var hash = this.width || 0;
  4276. hash = (hash * 397) ^ (this.height || 0);
  4277. return hash;
  4278. };
  4279. /**
  4280. * Updates the current size from the given one.
  4281. * Returns the updated Size.
  4282. */
  4283. Size.prototype.copyFrom = function (src) {
  4284. this.width = src.width;
  4285. this.height = src.height;
  4286. };
  4287. /**
  4288. * Updates in place the current Size from the given floats.
  4289. * Returns the updated Size.
  4290. */
  4291. Size.prototype.copyFromFloats = function (width, height) {
  4292. this.width = width;
  4293. this.height = height;
  4294. return this;
  4295. };
  4296. /**
  4297. * Updates in place the current Size from the given floats.
  4298. * Returns the updated Size.
  4299. */
  4300. Size.prototype.set = function (width, height) {
  4301. return this.copyFromFloats(width, height);
  4302. };
  4303. /**
  4304. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4305. */
  4306. Size.prototype.multiplyByFloats = function (w, h) {
  4307. return new Size(this.width * w, this.height * h);
  4308. };
  4309. /**
  4310. * Returns a new Size copied from the given one.
  4311. */
  4312. Size.prototype.clone = function () {
  4313. return new Size(this.width, this.height);
  4314. };
  4315. /**
  4316. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4317. */
  4318. Size.prototype.equals = function (other) {
  4319. if (!other) {
  4320. return false;
  4321. }
  4322. return (this.width === other.width) && (this.height === other.height);
  4323. };
  4324. Object.defineProperty(Size.prototype, "surface", {
  4325. /**
  4326. * Returns the surface of the Size : width * height (float).
  4327. */
  4328. get: function () {
  4329. return this.width * this.height;
  4330. },
  4331. enumerable: true,
  4332. configurable: true
  4333. });
  4334. /**
  4335. * Returns a new Size set to (0.0, 0.0)
  4336. */
  4337. Size.Zero = function () {
  4338. return new Size(0.0, 0.0);
  4339. };
  4340. /**
  4341. * Returns a new Size set as the addition result of the current Size and the given one.
  4342. */
  4343. Size.prototype.add = 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 as the subtraction result of the given one from the current Size.
  4349. */
  4350. Size.prototype.subtract = function (otherSize) {
  4351. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4352. return r;
  4353. };
  4354. /**
  4355. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4356. */
  4357. Size.Lerp = function (start, end, amount) {
  4358. var w = start.width + ((end.width - start.width) * amount);
  4359. var h = start.height + ((end.height - start.height) * amount);
  4360. return new Size(w, h);
  4361. };
  4362. return Size;
  4363. }());
  4364. BABYLON.Size = Size;
  4365. /**
  4366. * Class used to store quaternion data
  4367. * @see https://en.wikipedia.org/wiki/Quaternion
  4368. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4369. */
  4370. var Quaternion = /** @class */ (function () {
  4371. /**
  4372. * Creates a new Quaternion from the given floats
  4373. * @param x defines the first component (0 by default)
  4374. * @param y defines the second component (0 by default)
  4375. * @param z defines the third component (0 by default)
  4376. * @param w defines the fourth component (1.0 by default)
  4377. */
  4378. function Quaternion(
  4379. /** defines the first component (0 by default) */
  4380. x,
  4381. /** defines the second component (0 by default) */
  4382. y,
  4383. /** defines the third component (0 by default) */
  4384. z,
  4385. /** defines the fourth component (1.0 by default) */
  4386. w) {
  4387. if (x === void 0) { x = 0.0; }
  4388. if (y === void 0) { y = 0.0; }
  4389. if (z === void 0) { z = 0.0; }
  4390. if (w === void 0) { w = 1.0; }
  4391. this.x = x;
  4392. this.y = y;
  4393. this.z = z;
  4394. this.w = w;
  4395. }
  4396. /**
  4397. * Gets a string representation for the current quaternion
  4398. * @returns a string with the Quaternion coordinates
  4399. */
  4400. Quaternion.prototype.toString = function () {
  4401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4402. };
  4403. /**
  4404. * Gets the class name of the quaternion
  4405. * @returns the string "Quaternion"
  4406. */
  4407. Quaternion.prototype.getClassName = function () {
  4408. return "Quaternion";
  4409. };
  4410. /**
  4411. * Gets a hash code for this quaternion
  4412. * @returns the quaternion hash code
  4413. */
  4414. Quaternion.prototype.getHashCode = function () {
  4415. var hash = this.x || 0;
  4416. hash = (hash * 397) ^ (this.y || 0);
  4417. hash = (hash * 397) ^ (this.z || 0);
  4418. hash = (hash * 397) ^ (this.w || 0);
  4419. return hash;
  4420. };
  4421. /**
  4422. * Copy the quaternion to an array
  4423. * @returns a new array populated with 4 elements from the quaternion coordinates
  4424. */
  4425. Quaternion.prototype.asArray = function () {
  4426. return [this.x, this.y, this.z, this.w];
  4427. };
  4428. /**
  4429. * Check if two quaternions are equals
  4430. * @param otherQuaternion defines the second operand
  4431. * @return true if the current quaternion and the given one coordinates are strictly equals
  4432. */
  4433. Quaternion.prototype.equals = function (otherQuaternion) {
  4434. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4435. };
  4436. /**
  4437. * Clone the current quaternion
  4438. * @returns a new quaternion copied from the current one
  4439. */
  4440. Quaternion.prototype.clone = function () {
  4441. return new Quaternion(this.x, this.y, this.z, this.w);
  4442. };
  4443. /**
  4444. * Copy a quaternion to the current one
  4445. * @param other defines the other quaternion
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFrom = function (other) {
  4449. this.x = other.x;
  4450. this.y = other.y;
  4451. this.z = other.z;
  4452. this.w = other.w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion with the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4464. this.x = x;
  4465. this.y = y;
  4466. this.z = z;
  4467. this.w = w;
  4468. return this;
  4469. };
  4470. /**
  4471. * Updates the current quaternion from the given float coordinates
  4472. * @param x defines the x coordinate
  4473. * @param y defines the y coordinate
  4474. * @param z defines the z coordinate
  4475. * @param w defines the w coordinate
  4476. * @returns the updated current quaternion
  4477. */
  4478. Quaternion.prototype.set = function (x, y, z, w) {
  4479. return this.copyFromFloats(x, y, z, w);
  4480. };
  4481. /**
  4482. * Adds two quaternions
  4483. * @param other defines the second operand
  4484. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4485. */
  4486. Quaternion.prototype.add = function (other) {
  4487. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4488. };
  4489. /**
  4490. * Add a quaternion to the current one
  4491. * @param other defines the quaternion to add
  4492. * @returns the current quaternion
  4493. */
  4494. Quaternion.prototype.addInPlace = function (other) {
  4495. this.x += other.x;
  4496. this.y += other.y;
  4497. this.z += other.z;
  4498. this.w += other.w;
  4499. return this;
  4500. };
  4501. /**
  4502. * Subtract two quaternions
  4503. * @param other defines the second operand
  4504. * @returns a new quaternion as the subtraction result of the given one from the current one
  4505. */
  4506. Quaternion.prototype.subtract = function (other) {
  4507. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4508. };
  4509. /**
  4510. * Multiplies the current quaternion by a scale factor
  4511. * @param value defines the scale factor
  4512. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4513. */
  4514. Quaternion.prototype.scale = function (value) {
  4515. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4516. };
  4517. /**
  4518. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4519. * @param scale defines the scale factor
  4520. * @param result defines the Quaternion object where to store the result
  4521. * @returns the unmodified current quaternion
  4522. */
  4523. Quaternion.prototype.scaleToRef = function (scale, result) {
  4524. result.x = this.x * scale;
  4525. result.y = this.y * scale;
  4526. result.z = this.z * scale;
  4527. result.w = this.w * scale;
  4528. return this;
  4529. };
  4530. /**
  4531. * Multiplies in place the current quaternion by a scale factor
  4532. * @param value defines the scale factor
  4533. * @returns the current modified quaternion
  4534. */
  4535. Quaternion.prototype.scaleInPlace = function (value) {
  4536. this.x *= value;
  4537. this.y *= value;
  4538. this.z *= value;
  4539. this.w *= value;
  4540. return this;
  4541. };
  4542. /**
  4543. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4544. * @param scale defines the scale factor
  4545. * @param result defines the Quaternion object where to store the result
  4546. * @returns the unmodified current quaternion
  4547. */
  4548. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4549. result.x += this.x * scale;
  4550. result.y += this.y * scale;
  4551. result.z += this.z * scale;
  4552. result.w += this.w * scale;
  4553. return this;
  4554. };
  4555. /**
  4556. * Multiplies two quaternions
  4557. * @param q1 defines the second operand
  4558. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4559. */
  4560. Quaternion.prototype.multiply = function (q1) {
  4561. var result = new Quaternion(0, 0, 0, 1.0);
  4562. this.multiplyToRef(q1, result);
  4563. return result;
  4564. };
  4565. /**
  4566. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4567. * @param q1 defines the second operand
  4568. * @param result defines the target quaternion
  4569. * @returns the current quaternion
  4570. */
  4571. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4572. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4573. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4574. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4575. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4576. result.copyFromFloats(x, y, z, w);
  4577. return this;
  4578. };
  4579. /**
  4580. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4581. * @param q1 defines the second operand
  4582. * @returns the currentupdated quaternion
  4583. */
  4584. Quaternion.prototype.multiplyInPlace = function (q1) {
  4585. this.multiplyToRef(q1, this);
  4586. return this;
  4587. };
  4588. /**
  4589. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4590. * @param ref defines the target quaternion
  4591. * @returns the current quaternion
  4592. */
  4593. Quaternion.prototype.conjugateToRef = function (ref) {
  4594. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4595. return this;
  4596. };
  4597. /**
  4598. * Conjugates in place (1-q) the current quaternion
  4599. * @returns the current updated quaternion
  4600. */
  4601. Quaternion.prototype.conjugateInPlace = function () {
  4602. this.x *= -1;
  4603. this.y *= -1;
  4604. this.z *= -1;
  4605. return this;
  4606. };
  4607. /**
  4608. * Conjugates in place (1-q) the current quaternion
  4609. * @returns a new quaternion
  4610. */
  4611. Quaternion.prototype.conjugate = function () {
  4612. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4613. return result;
  4614. };
  4615. /**
  4616. * Gets length of current quaternion
  4617. * @returns the quaternion length (float)
  4618. */
  4619. Quaternion.prototype.length = function () {
  4620. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4621. };
  4622. /**
  4623. * Normalize in place the current quaternion
  4624. * @returns the current updated quaternion
  4625. */
  4626. Quaternion.prototype.normalize = function () {
  4627. var length = 1.0 / this.length();
  4628. this.x *= length;
  4629. this.y *= length;
  4630. this.z *= length;
  4631. this.w *= length;
  4632. return this;
  4633. };
  4634. /**
  4635. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4636. * @param order is a reserved parameter and is ignore for now
  4637. * @returns a new Vector3 containing the Euler angles
  4638. */
  4639. Quaternion.prototype.toEulerAngles = function (order) {
  4640. if (order === void 0) { order = "YZX"; }
  4641. var result = Vector3.Zero();
  4642. this.toEulerAnglesToRef(result, order);
  4643. return result;
  4644. };
  4645. /**
  4646. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4647. * @param result defines the vector which will be filled with the Euler angles
  4648. * @param order is a reserved parameter and is ignore for now
  4649. * @returns the current unchanged quaternion
  4650. */
  4651. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4652. if (order === void 0) { order = "YZX"; }
  4653. var qz = this.z;
  4654. var qx = this.x;
  4655. var qy = this.y;
  4656. var qw = this.w;
  4657. var sqw = qw * qw;
  4658. var sqz = qz * qz;
  4659. var sqx = qx * qx;
  4660. var sqy = qy * qy;
  4661. var zAxisY = qy * qz - qx * qw;
  4662. var limit = .4999999;
  4663. if (zAxisY < -limit) {
  4664. result.y = 2 * Math.atan2(qy, qw);
  4665. result.x = Math.PI / 2;
  4666. result.z = 0;
  4667. }
  4668. else if (zAxisY > limit) {
  4669. result.y = 2 * Math.atan2(qy, qw);
  4670. result.x = -Math.PI / 2;
  4671. result.z = 0;
  4672. }
  4673. else {
  4674. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4675. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4676. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4677. }
  4678. return this;
  4679. };
  4680. /**
  4681. * Updates the given rotation matrix with the current quaternion values
  4682. * @param result defines the target matrix
  4683. * @returns the current unchanged quaternion
  4684. */
  4685. Quaternion.prototype.toRotationMatrix = function (result) {
  4686. var xx = this.x * this.x;
  4687. var yy = this.y * this.y;
  4688. var zz = this.z * this.z;
  4689. var xy = this.x * this.y;
  4690. var zw = this.z * this.w;
  4691. var zx = this.z * this.x;
  4692. var yw = this.y * this.w;
  4693. var yz = this.y * this.z;
  4694. var xw = this.x * this.w;
  4695. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4696. result.m[1] = 2.0 * (xy + zw);
  4697. result.m[2] = 2.0 * (zx - yw);
  4698. result.m[3] = 0;
  4699. result.m[4] = 2.0 * (xy - zw);
  4700. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4701. result.m[6] = 2.0 * (yz + xw);
  4702. result.m[7] = 0;
  4703. result.m[8] = 2.0 * (zx + yw);
  4704. result.m[9] = 2.0 * (yz - xw);
  4705. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4706. result.m[11] = 0;
  4707. result.m[12] = 0;
  4708. result.m[13] = 0;
  4709. result.m[14] = 0;
  4710. result.m[15] = 1.0;
  4711. result._markAsUpdated();
  4712. return this;
  4713. };
  4714. /**
  4715. * Updates the current quaternion from the given rotation matrix values
  4716. * @param matrix defines the source matrix
  4717. * @returns the current updated quaternion
  4718. */
  4719. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4720. Quaternion.FromRotationMatrixToRef(matrix, this);
  4721. return this;
  4722. };
  4723. // Statics
  4724. /**
  4725. * Creates a new quaternion from a rotation matrix
  4726. * @param matrix defines the source matrix
  4727. * @returns a new quaternion created from the given rotation matrix values
  4728. */
  4729. Quaternion.FromRotationMatrix = function (matrix) {
  4730. var result = new Quaternion();
  4731. Quaternion.FromRotationMatrixToRef(matrix, result);
  4732. return result;
  4733. };
  4734. /**
  4735. * Updates the given quaternion with the given rotation matrix values
  4736. * @param matrix defines the source matrix
  4737. * @param result defines the target quaternion
  4738. */
  4739. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4740. var data = matrix.m;
  4741. var m11 = data[0], m12 = data[4], m13 = data[8];
  4742. var m21 = data[1], m22 = data[5], m23 = data[9];
  4743. var m31 = data[2], m32 = data[6], m33 = data[10];
  4744. var trace = m11 + m22 + m33;
  4745. var s;
  4746. if (trace > 0) {
  4747. s = 0.5 / Math.sqrt(trace + 1.0);
  4748. result.w = 0.25 / s;
  4749. result.x = (m32 - m23) * s;
  4750. result.y = (m13 - m31) * s;
  4751. result.z = (m21 - m12) * s;
  4752. }
  4753. else if (m11 > m22 && m11 > m33) {
  4754. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4755. result.w = (m32 - m23) / s;
  4756. result.x = 0.25 * s;
  4757. result.y = (m12 + m21) / s;
  4758. result.z = (m13 + m31) / s;
  4759. }
  4760. else if (m22 > m33) {
  4761. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4762. result.w = (m13 - m31) / s;
  4763. result.x = (m12 + m21) / s;
  4764. result.y = 0.25 * s;
  4765. result.z = (m23 + m32) / s;
  4766. }
  4767. else {
  4768. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4769. result.w = (m21 - m12) / s;
  4770. result.x = (m13 + m31) / s;
  4771. result.y = (m23 + m32) / s;
  4772. result.z = 0.25 * s;
  4773. }
  4774. };
  4775. /**
  4776. * Returns the dot product (float) between the quaternions "left" and "right"
  4777. * @param left defines the left operand
  4778. * @param right defines the right operand
  4779. * @returns the dot product
  4780. */
  4781. Quaternion.Dot = function (left, right) {
  4782. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4783. };
  4784. /**
  4785. * Checks if the two quaternions are close to each other
  4786. * @param quat0 defines the first quaternion to check
  4787. * @param quat1 defines the second quaternion to check
  4788. * @returns true if the two quaternions are close to each other
  4789. */
  4790. Quaternion.AreClose = function (quat0, quat1) {
  4791. var dot = Quaternion.Dot(quat0, quat1);
  4792. return dot >= 0;
  4793. };
  4794. /**
  4795. * Creates an empty quaternion
  4796. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4797. */
  4798. Quaternion.Zero = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4800. };
  4801. /**
  4802. * Inverse a given quaternion
  4803. * @param q defines the source quaternion
  4804. * @returns a new quaternion as the inverted current quaternion
  4805. */
  4806. Quaternion.Inverse = function (q) {
  4807. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4808. };
  4809. /**
  4810. * Creates an identity quaternion
  4811. * @returns the identity quaternion
  4812. */
  4813. Quaternion.Identity = function () {
  4814. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4815. };
  4816. /**
  4817. * Gets a boolean indicating if the given quaternion is identity
  4818. * @param quaternion defines the quaternion to check
  4819. * @returns true if the quaternion is identity
  4820. */
  4821. Quaternion.IsIdentity = function (quaternion) {
  4822. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4823. };
  4824. /**
  4825. * Creates a quaternion from a rotation around an axis
  4826. * @param axis defines the axis to use
  4827. * @param angle defines the angle to use
  4828. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4829. */
  4830. Quaternion.RotationAxis = function (axis, angle) {
  4831. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4832. };
  4833. /**
  4834. * Creates a rotation around an axis and stores it into the given quaternion
  4835. * @param axis defines the axis to use
  4836. * @param angle defines the angle to use
  4837. * @param result defines the target quaternion
  4838. * @returns the target quaternion
  4839. */
  4840. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4841. var sin = Math.sin(angle / 2);
  4842. axis.normalize();
  4843. result.w = Math.cos(angle / 2);
  4844. result.x = axis.x * sin;
  4845. result.y = axis.y * sin;
  4846. result.z = axis.z * sin;
  4847. return result;
  4848. };
  4849. /**
  4850. * Creates a new quaternion from data stored into an array
  4851. * @param array defines the data source
  4852. * @param offset defines the offset in the source array where the data starts
  4853. * @returns a new quaternion
  4854. */
  4855. Quaternion.FromArray = function (array, offset) {
  4856. if (!offset) {
  4857. offset = 0;
  4858. }
  4859. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4860. };
  4861. /**
  4862. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4863. * @param yaw defines the rotation around Y axis
  4864. * @param pitch defines the rotation around X axis
  4865. * @param roll defines the rotation around Z axis
  4866. * @returns the new quaternion
  4867. */
  4868. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4869. var q = new Quaternion();
  4870. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4871. return q;
  4872. };
  4873. /**
  4874. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4875. * @param yaw defines the rotation around Y axis
  4876. * @param pitch defines the rotation around X axis
  4877. * @param roll defines the rotation around Z axis
  4878. * @param result defines the target quaternion
  4879. */
  4880. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4881. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4882. var halfRoll = roll * 0.5;
  4883. var halfPitch = pitch * 0.5;
  4884. var halfYaw = yaw * 0.5;
  4885. var sinRoll = Math.sin(halfRoll);
  4886. var cosRoll = Math.cos(halfRoll);
  4887. var sinPitch = Math.sin(halfPitch);
  4888. var cosPitch = Math.cos(halfPitch);
  4889. var sinYaw = Math.sin(halfYaw);
  4890. var cosYaw = Math.cos(halfYaw);
  4891. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4892. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4893. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4894. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4895. };
  4896. /**
  4897. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4898. * @param alpha defines the rotation around first axis
  4899. * @param beta defines the rotation around second axis
  4900. * @param gamma defines the rotation around third axis
  4901. * @returns the new quaternion
  4902. */
  4903. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4904. var result = new Quaternion();
  4905. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4906. return result;
  4907. };
  4908. /**
  4909. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4910. * @param alpha defines the rotation around first axis
  4911. * @param beta defines the rotation around second axis
  4912. * @param gamma defines the rotation around third axis
  4913. * @param result defines the target quaternion
  4914. */
  4915. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4916. // Produces a quaternion from Euler angles in the z-x-z orientation
  4917. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4918. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4919. var halfBeta = beta * 0.5;
  4920. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4921. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4922. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4923. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4924. };
  4925. /**
  4926. * 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)
  4927. * @param axis1 defines the first axis
  4928. * @param axis2 defines the second axis
  4929. * @param axis3 defines the third axis
  4930. * @returns the new quaternion
  4931. */
  4932. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4933. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4934. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4935. return quat;
  4936. };
  4937. /**
  4938. * 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
  4939. * @param axis1 defines the first axis
  4940. * @param axis2 defines the second axis
  4941. * @param axis3 defines the third axis
  4942. * @param ref defines the target quaternion
  4943. */
  4944. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4945. var rotMat = MathTmp.Matrix[0];
  4946. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4947. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4948. };
  4949. /**
  4950. * Interpolates between two quaternions
  4951. * @param left defines first quaternion
  4952. * @param right defines second quaternion
  4953. * @param amount defines the gradient to use
  4954. * @returns the new interpolated quaternion
  4955. */
  4956. Quaternion.Slerp = function (left, right, amount) {
  4957. var result = Quaternion.Identity();
  4958. Quaternion.SlerpToRef(left, right, amount, result);
  4959. return result;
  4960. };
  4961. /**
  4962. * Interpolates between two quaternions and stores it into a target quaternion
  4963. * @param left defines first quaternion
  4964. * @param right defines second quaternion
  4965. * @param amount defines the gradient to use
  4966. * @param result defines the target quaternion
  4967. */
  4968. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4969. var num2;
  4970. var num3;
  4971. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4972. var flag = false;
  4973. if (num4 < 0) {
  4974. flag = true;
  4975. num4 = -num4;
  4976. }
  4977. if (num4 > 0.999999) {
  4978. num3 = 1 - amount;
  4979. num2 = flag ? -amount : amount;
  4980. }
  4981. else {
  4982. var num5 = Math.acos(num4);
  4983. var num6 = (1.0 / Math.sin(num5));
  4984. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4985. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4986. }
  4987. result.x = (num3 * left.x) + (num2 * right.x);
  4988. result.y = (num3 * left.y) + (num2 * right.y);
  4989. result.z = (num3 * left.z) + (num2 * right.z);
  4990. result.w = (num3 * left.w) + (num2 * right.w);
  4991. };
  4992. /**
  4993. * Interpolate between two quaternions using Hermite interpolation
  4994. * @param value1 defines first quaternion
  4995. * @param tangent1 defines the incoming tangent
  4996. * @param value2 defines second quaternion
  4997. * @param tangent2 defines the outgoing tangent
  4998. * @param amount defines the target quaternion
  4999. * @returns the new interpolated quaternion
  5000. */
  5001. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5002. var squared = amount * amount;
  5003. var cubed = amount * squared;
  5004. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5005. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5006. var part3 = (cubed - (2.0 * squared)) + amount;
  5007. var part4 = cubed - squared;
  5008. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5009. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5010. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5011. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5012. return new Quaternion(x, y, z, w);
  5013. };
  5014. return Quaternion;
  5015. }());
  5016. BABYLON.Quaternion = Quaternion;
  5017. /**
  5018. * Class used to store matrix data (4x4)
  5019. */
  5020. var Matrix = /** @class */ (function () {
  5021. /**
  5022. * Creates an empty matrix (filled with zeros)
  5023. */
  5024. function Matrix() {
  5025. this._isIdentity = false;
  5026. this._isIdentityDirty = true;
  5027. /**
  5028. * Gets or sets the internal data of the matrix
  5029. */
  5030. this.m = new Float32Array(16);
  5031. this._markAsUpdated();
  5032. }
  5033. /** @hidden */
  5034. Matrix.prototype._markAsUpdated = function () {
  5035. this.updateFlag = Matrix._updateFlagSeed++;
  5036. this._isIdentityDirty = true;
  5037. };
  5038. // Properties
  5039. /**
  5040. * Check if the current matrix is indentity
  5041. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5042. * @returns true is the matrix is the identity matrix
  5043. */
  5044. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5045. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5046. if (this._isIdentityDirty) {
  5047. this._isIdentityDirty = false;
  5048. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5049. this._isIdentity = false;
  5050. }
  5051. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5052. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5053. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5054. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5055. this._isIdentity = false;
  5056. }
  5057. else {
  5058. this._isIdentity = true;
  5059. }
  5060. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5061. this._isIdentity = false;
  5062. }
  5063. }
  5064. return this._isIdentity;
  5065. };
  5066. /**
  5067. * Gets the determinant of the matrix
  5068. * @returns the matrix determinant
  5069. */
  5070. Matrix.prototype.determinant = function () {
  5071. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5072. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5073. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5074. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5075. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5076. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5077. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5078. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5079. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5080. };
  5081. // Methods
  5082. /**
  5083. * Returns the matrix as a Float32Array
  5084. * @returns the matrix underlying array
  5085. */
  5086. Matrix.prototype.toArray = function () {
  5087. return this.m;
  5088. };
  5089. /**
  5090. * Returns the matrix as a Float32Array
  5091. * @returns the matrix underlying array.
  5092. */
  5093. Matrix.prototype.asArray = function () {
  5094. return this.toArray();
  5095. };
  5096. /**
  5097. * Inverts the current matrix in place
  5098. * @returns the current inverted matrix
  5099. */
  5100. Matrix.prototype.invert = function () {
  5101. this.invertToRef(this);
  5102. return this;
  5103. };
  5104. /**
  5105. * Sets all the matrix elements to zero
  5106. * @returns the current matrix
  5107. */
  5108. Matrix.prototype.reset = function () {
  5109. for (var index = 0; index < 16; index++) {
  5110. this.m[index] = 0.0;
  5111. }
  5112. this._markAsUpdated();
  5113. return this;
  5114. };
  5115. /**
  5116. * Adds the current matrix with a second one
  5117. * @param other defines the matrix to add
  5118. * @returns a new matrix as the addition of the current matrix and the given one
  5119. */
  5120. Matrix.prototype.add = function (other) {
  5121. var result = new Matrix();
  5122. this.addToRef(other, result);
  5123. return result;
  5124. };
  5125. /**
  5126. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5127. * @param other defines the matrix to add
  5128. * @param result defines the target matrix
  5129. * @returns the current matrix
  5130. */
  5131. Matrix.prototype.addToRef = function (other, result) {
  5132. for (var index = 0; index < 16; index++) {
  5133. result.m[index] = this.m[index] + other.m[index];
  5134. }
  5135. result._markAsUpdated();
  5136. return this;
  5137. };
  5138. /**
  5139. * Adds in place the given matrix to the current matrix
  5140. * @param other defines the second operand
  5141. * @returns the current updated matrix
  5142. */
  5143. Matrix.prototype.addToSelf = function (other) {
  5144. for (var index = 0; index < 16; index++) {
  5145. this.m[index] += other.m[index];
  5146. }
  5147. this._markAsUpdated();
  5148. return this;
  5149. };
  5150. /**
  5151. * Sets the given matrix to the current inverted Matrix
  5152. * @param other defines the target matrix
  5153. * @returns the unmodified current matrix
  5154. */
  5155. Matrix.prototype.invertToRef = function (other) {
  5156. var l1 = this.m[0];
  5157. var l2 = this.m[1];
  5158. var l3 = this.m[2];
  5159. var l4 = this.m[3];
  5160. var l5 = this.m[4];
  5161. var l6 = this.m[5];
  5162. var l7 = this.m[6];
  5163. var l8 = this.m[7];
  5164. var l9 = this.m[8];
  5165. var l10 = this.m[9];
  5166. var l11 = this.m[10];
  5167. var l12 = this.m[11];
  5168. var l13 = this.m[12];
  5169. var l14 = this.m[13];
  5170. var l15 = this.m[14];
  5171. var l16 = this.m[15];
  5172. var l17 = (l11 * l16) - (l12 * l15);
  5173. var l18 = (l10 * l16) - (l12 * l14);
  5174. var l19 = (l10 * l15) - (l11 * l14);
  5175. var l20 = (l9 * l16) - (l12 * l13);
  5176. var l21 = (l9 * l15) - (l11 * l13);
  5177. var l22 = (l9 * l14) - (l10 * l13);
  5178. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5179. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5180. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5181. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5182. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5183. var l28 = (l7 * l16) - (l8 * l15);
  5184. var l29 = (l6 * l16) - (l8 * l14);
  5185. var l30 = (l6 * l15) - (l7 * l14);
  5186. var l31 = (l5 * l16) - (l8 * l13);
  5187. var l32 = (l5 * l15) - (l7 * l13);
  5188. var l33 = (l5 * l14) - (l6 * l13);
  5189. var l34 = (l7 * l12) - (l8 * l11);
  5190. var l35 = (l6 * l12) - (l8 * l10);
  5191. var l36 = (l6 * l11) - (l7 * l10);
  5192. var l37 = (l5 * l12) - (l8 * l9);
  5193. var l38 = (l5 * l11) - (l7 * l9);
  5194. var l39 = (l5 * l10) - (l6 * l9);
  5195. other.m[0] = l23 * l27;
  5196. other.m[4] = l24 * l27;
  5197. other.m[8] = l25 * l27;
  5198. other.m[12] = l26 * l27;
  5199. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5200. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5201. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5202. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5203. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5204. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5205. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5206. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5207. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5208. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5209. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5210. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5211. other._markAsUpdated();
  5212. return this;
  5213. };
  5214. /**
  5215. * Inserts the translation vector (using 3 floats) in the current matrix
  5216. * @param x defines the 1st component of the translation
  5217. * @param y defines the 2nd component of the translation
  5218. * @param z defines the 3rd component of the translation
  5219. * @returns the current updated matrix
  5220. */
  5221. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5222. this.m[12] = x;
  5223. this.m[13] = y;
  5224. this.m[14] = z;
  5225. this._markAsUpdated();
  5226. return this;
  5227. };
  5228. /**
  5229. * Inserts the translation vector in the current matrix
  5230. * @param vector3 defines the translation to insert
  5231. * @returns the current updated matrix
  5232. */
  5233. Matrix.prototype.setTranslation = function (vector3) {
  5234. this.m[12] = vector3.x;
  5235. this.m[13] = vector3.y;
  5236. this.m[14] = vector3.z;
  5237. this._markAsUpdated();
  5238. return this;
  5239. };
  5240. /**
  5241. * Gets the translation value of the current matrix
  5242. * @returns a new Vector3 as the extracted translation from the matrix
  5243. */
  5244. Matrix.prototype.getTranslation = function () {
  5245. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5246. };
  5247. /**
  5248. * Fill a Vector3 with the extracted translation from the matrix
  5249. * @param result defines the Vector3 where to store the translation
  5250. * @returns the current matrix
  5251. */
  5252. Matrix.prototype.getTranslationToRef = function (result) {
  5253. result.x = this.m[12];
  5254. result.y = this.m[13];
  5255. result.z = this.m[14];
  5256. return this;
  5257. };
  5258. /**
  5259. * Remove rotation and scaling part from the matrix
  5260. * @returns the updated matrix
  5261. */
  5262. Matrix.prototype.removeRotationAndScaling = function () {
  5263. this.setRowFromFloats(0, 1, 0, 0, 0);
  5264. this.setRowFromFloats(1, 0, 1, 0, 0);
  5265. this.setRowFromFloats(2, 0, 0, 1, 0);
  5266. return this;
  5267. };
  5268. /**
  5269. * Multiply two matrices
  5270. * @param other defines the second operand
  5271. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5272. */
  5273. Matrix.prototype.multiply = function (other) {
  5274. var result = new Matrix();
  5275. this.multiplyToRef(other, result);
  5276. return result;
  5277. };
  5278. /**
  5279. * Copy the current matrix from the given one
  5280. * @param other defines the source matrix
  5281. * @returns the current updated matrix
  5282. */
  5283. Matrix.prototype.copyFrom = function (other) {
  5284. for (var index = 0; index < 16; index++) {
  5285. this.m[index] = other.m[index];
  5286. }
  5287. this._markAsUpdated();
  5288. return this;
  5289. };
  5290. /**
  5291. * Populates the given array from the starting index with the current matrix values
  5292. * @param array defines the target array
  5293. * @param offset defines the offset in the target array where to start storing values
  5294. * @returns the current matrix
  5295. */
  5296. Matrix.prototype.copyToArray = function (array, offset) {
  5297. if (offset === void 0) { offset = 0; }
  5298. for (var index = 0; index < 16; index++) {
  5299. array[offset + index] = this.m[index];
  5300. }
  5301. return this;
  5302. };
  5303. /**
  5304. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5305. * @param other defines the second operand
  5306. * @param result defines the matrix where to store the multiplication
  5307. * @returns the current matrix
  5308. */
  5309. Matrix.prototype.multiplyToRef = function (other, result) {
  5310. this.multiplyToArray(other, result.m, 0);
  5311. result._markAsUpdated();
  5312. return this;
  5313. };
  5314. /**
  5315. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5316. * @param other defines the second operand
  5317. * @param result defines the array where to store the multiplication
  5318. * @param offset defines the offset in the target array where to start storing values
  5319. * @returns the current matrix
  5320. */
  5321. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5322. var tm0 = this.m[0];
  5323. var tm1 = this.m[1];
  5324. var tm2 = this.m[2];
  5325. var tm3 = this.m[3];
  5326. var tm4 = this.m[4];
  5327. var tm5 = this.m[5];
  5328. var tm6 = this.m[6];
  5329. var tm7 = this.m[7];
  5330. var tm8 = this.m[8];
  5331. var tm9 = this.m[9];
  5332. var tm10 = this.m[10];
  5333. var tm11 = this.m[11];
  5334. var tm12 = this.m[12];
  5335. var tm13 = this.m[13];
  5336. var tm14 = this.m[14];
  5337. var tm15 = this.m[15];
  5338. var om0 = other.m[0];
  5339. var om1 = other.m[1];
  5340. var om2 = other.m[2];
  5341. var om3 = other.m[3];
  5342. var om4 = other.m[4];
  5343. var om5 = other.m[5];
  5344. var om6 = other.m[6];
  5345. var om7 = other.m[7];
  5346. var om8 = other.m[8];
  5347. var om9 = other.m[9];
  5348. var om10 = other.m[10];
  5349. var om11 = other.m[11];
  5350. var om12 = other.m[12];
  5351. var om13 = other.m[13];
  5352. var om14 = other.m[14];
  5353. var om15 = other.m[15];
  5354. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5355. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5356. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5357. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5358. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5359. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5360. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5361. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5362. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5363. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5364. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5365. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5366. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5367. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5368. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5369. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5370. return this;
  5371. };
  5372. /**
  5373. * Check equality between this matrix and a second one
  5374. * @param value defines the second matrix to compare
  5375. * @returns true is the current matrix and the given one values are strictly equal
  5376. */
  5377. Matrix.prototype.equals = function (value) {
  5378. return value &&
  5379. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5380. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5381. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5382. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5383. };
  5384. /**
  5385. * Clone the current matrix
  5386. * @returns a new matrix from the current matrix
  5387. */
  5388. Matrix.prototype.clone = function () {
  5389. 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]);
  5390. };
  5391. /**
  5392. * Returns the name of the current matrix class
  5393. * @returns the string "Matrix"
  5394. */
  5395. Matrix.prototype.getClassName = function () {
  5396. return "Matrix";
  5397. };
  5398. /**
  5399. * Gets the hash code of the current matrix
  5400. * @returns the hash code
  5401. */
  5402. Matrix.prototype.getHashCode = function () {
  5403. var hash = this.m[0] || 0;
  5404. for (var i = 1; i < 16; i++) {
  5405. hash = (hash * 397) ^ (this.m[i] || 0);
  5406. }
  5407. return hash;
  5408. };
  5409. /**
  5410. * Decomposes the current Matrix into a translation, rotation and scaling components
  5411. * @param scale defines the scale vector3 given as a reference to update
  5412. * @param rotation defines the rotation quaternion given as a reference to update
  5413. * @param translation defines the translation vector3 given as a reference to update
  5414. * @returns true if operation was successful
  5415. */
  5416. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5417. if (translation) {
  5418. translation.x = this.m[12];
  5419. translation.y = this.m[13];
  5420. translation.z = this.m[14];
  5421. }
  5422. scale = scale || MathTmp.Vector3[0];
  5423. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5424. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5425. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5426. if (this.determinant() <= 0) {
  5427. scale.y *= -1;
  5428. }
  5429. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5430. if (rotation) {
  5431. rotation.x = 0;
  5432. rotation.y = 0;
  5433. rotation.z = 0;
  5434. rotation.w = 1;
  5435. }
  5436. return false;
  5437. }
  5438. if (rotation) {
  5439. 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]);
  5440. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5441. }
  5442. return true;
  5443. };
  5444. /**
  5445. * Gets specific row of the matrix
  5446. * @param index defines the number of the row to get
  5447. * @returns the index-th row of the current matrix as a new Vector4
  5448. */
  5449. Matrix.prototype.getRow = function (index) {
  5450. if (index < 0 || index > 3) {
  5451. return null;
  5452. }
  5453. var i = index * 4;
  5454. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5455. };
  5456. /**
  5457. * Sets the index-th row of the current matrix to the vector4 values
  5458. * @param index defines the number of the row to set
  5459. * @param row defines the target vector4
  5460. * @returns the updated current matrix
  5461. */
  5462. Matrix.prototype.setRow = function (index, row) {
  5463. if (index < 0 || index > 3) {
  5464. return this;
  5465. }
  5466. var i = index * 4;
  5467. this.m[i + 0] = row.x;
  5468. this.m[i + 1] = row.y;
  5469. this.m[i + 2] = row.z;
  5470. this.m[i + 3] = row.w;
  5471. this._markAsUpdated();
  5472. return this;
  5473. };
  5474. /**
  5475. * Compute the transpose of the matrix
  5476. * @returns the new transposed matrix
  5477. */
  5478. Matrix.prototype.transpose = function () {
  5479. return Matrix.Transpose(this);
  5480. };
  5481. /**
  5482. * Compute the transpose of the matrix and store it in a given matrix
  5483. * @param result defines the target matrix
  5484. * @returns the current matrix
  5485. */
  5486. Matrix.prototype.transposeToRef = function (result) {
  5487. Matrix.TransposeToRef(this, result);
  5488. return this;
  5489. };
  5490. /**
  5491. * Sets the index-th row of the current matrix with the given 4 x float values
  5492. * @param index defines the row index
  5493. * @param x defines the x component to set
  5494. * @param y defines the y component to set
  5495. * @param z defines the z component to set
  5496. * @param w defines the w component to set
  5497. * @returns the updated current matrix
  5498. */
  5499. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5500. if (index < 0 || index > 3) {
  5501. return this;
  5502. }
  5503. var i = index * 4;
  5504. this.m[i + 0] = x;
  5505. this.m[i + 1] = y;
  5506. this.m[i + 2] = z;
  5507. this.m[i + 3] = w;
  5508. this._markAsUpdated();
  5509. return this;
  5510. };
  5511. /**
  5512. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5513. * @param scale defines the scale factor
  5514. * @returns a new matrix
  5515. */
  5516. Matrix.prototype.scale = function (scale) {
  5517. var result = new Matrix();
  5518. this.scaleToRef(scale, result);
  5519. return result;
  5520. };
  5521. /**
  5522. * Scale the current matrix values by a factor to a given result matrix
  5523. * @param scale defines the scale factor
  5524. * @param result defines the matrix to store the result
  5525. * @returns the current matrix
  5526. */
  5527. Matrix.prototype.scaleToRef = function (scale, result) {
  5528. for (var index = 0; index < 16; index++) {
  5529. result.m[index] = this.m[index] * scale;
  5530. }
  5531. result._markAsUpdated();
  5532. return this;
  5533. };
  5534. /**
  5535. * Scale the current matrix values by a factor and add the result to a given matrix
  5536. * @param scale defines the scale factor
  5537. * @param result defines the Matrix to store the result
  5538. * @returns the current matrix
  5539. */
  5540. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5541. for (var index = 0; index < 16; index++) {
  5542. result.m[index] += this.m[index] * scale;
  5543. }
  5544. result._markAsUpdated();
  5545. return this;
  5546. };
  5547. /**
  5548. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5549. * @param ref matrix to store the result
  5550. */
  5551. Matrix.prototype.toNormalMatrix = function (ref) {
  5552. this.invertToRef(ref);
  5553. ref.transpose();
  5554. var m = ref.m;
  5555. 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);
  5556. };
  5557. /**
  5558. * Gets only rotation part of the current matrix
  5559. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5560. */
  5561. Matrix.prototype.getRotationMatrix = function () {
  5562. var result = Matrix.Identity();
  5563. this.getRotationMatrixToRef(result);
  5564. return result;
  5565. };
  5566. /**
  5567. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5568. * @param result defines the target matrix to store data to
  5569. * @returns the current matrix
  5570. */
  5571. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5572. var m = this.m;
  5573. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5574. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5575. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5576. if (this.determinant() <= 0) {
  5577. sy *= -1;
  5578. }
  5579. if (sx === 0 || sy === 0 || sz === 0) {
  5580. Matrix.IdentityToRef(result);
  5581. }
  5582. else {
  5583. 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);
  5584. }
  5585. return this;
  5586. };
  5587. // Statics
  5588. /**
  5589. * Creates a matrix from an array
  5590. * @param array defines the source array
  5591. * @param offset defines an offset in the source array
  5592. * @returns a new Matrix set from the starting index of the given array
  5593. */
  5594. Matrix.FromArray = function (array, offset) {
  5595. var result = new Matrix();
  5596. if (!offset) {
  5597. offset = 0;
  5598. }
  5599. Matrix.FromArrayToRef(array, offset, result);
  5600. return result;
  5601. };
  5602. /**
  5603. * Copy the content of an array into a given matrix
  5604. * @param array defines the source array
  5605. * @param offset defines an offset in the source array
  5606. * @param result defines the target matrix
  5607. */
  5608. Matrix.FromArrayToRef = function (array, offset, result) {
  5609. for (var index = 0; index < 16; index++) {
  5610. result.m[index] = array[index + offset];
  5611. }
  5612. result._markAsUpdated();
  5613. };
  5614. /**
  5615. * Stores an array into a matrix after having multiplied each component by a given factor
  5616. * @param array defines the source array
  5617. * @param offset defines the offset in the source array
  5618. * @param scale defines the scaling factor
  5619. * @param result defines the target matrix
  5620. */
  5621. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5622. for (var index = 0; index < 16; index++) {
  5623. result.m[index] = array[index + offset] * scale;
  5624. }
  5625. result._markAsUpdated();
  5626. };
  5627. /**
  5628. * Stores a list of values (16) inside a given matrix
  5629. * @param initialM11 defines 1st value of 1st row
  5630. * @param initialM12 defines 2nd value of 1st row
  5631. * @param initialM13 defines 3rd value of 1st row
  5632. * @param initialM14 defines 4th value of 1st row
  5633. * @param initialM21 defines 1st value of 2nd row
  5634. * @param initialM22 defines 2nd value of 2nd row
  5635. * @param initialM23 defines 3rd value of 2nd row
  5636. * @param initialM24 defines 4th value of 2nd row
  5637. * @param initialM31 defines 1st value of 3rd row
  5638. * @param initialM32 defines 2nd value of 3rd row
  5639. * @param initialM33 defines 3rd value of 3rd row
  5640. * @param initialM34 defines 4th value of 3rd row
  5641. * @param initialM41 defines 1st value of 4th row
  5642. * @param initialM42 defines 2nd value of 4th row
  5643. * @param initialM43 defines 3rd value of 4th row
  5644. * @param initialM44 defines 4th value of 4th row
  5645. * @param result defines the target matrix
  5646. */
  5647. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5648. result.m[0] = initialM11;
  5649. result.m[1] = initialM12;
  5650. result.m[2] = initialM13;
  5651. result.m[3] = initialM14;
  5652. result.m[4] = initialM21;
  5653. result.m[5] = initialM22;
  5654. result.m[6] = initialM23;
  5655. result.m[7] = initialM24;
  5656. result.m[8] = initialM31;
  5657. result.m[9] = initialM32;
  5658. result.m[10] = initialM33;
  5659. result.m[11] = initialM34;
  5660. result.m[12] = initialM41;
  5661. result.m[13] = initialM42;
  5662. result.m[14] = initialM43;
  5663. result.m[15] = initialM44;
  5664. result._markAsUpdated();
  5665. };
  5666. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5667. /**
  5668. * Gets an identity matrix that must not be updated
  5669. */
  5670. get: function () {
  5671. return Matrix._identityReadOnly;
  5672. },
  5673. enumerable: true,
  5674. configurable: true
  5675. });
  5676. /**
  5677. * Creates new matrix from a list of values (16)
  5678. * @param initialM11 defines 1st value of 1st row
  5679. * @param initialM12 defines 2nd value of 1st row
  5680. * @param initialM13 defines 3rd value of 1st row
  5681. * @param initialM14 defines 4th value of 1st row
  5682. * @param initialM21 defines 1st value of 2nd row
  5683. * @param initialM22 defines 2nd value of 2nd row
  5684. * @param initialM23 defines 3rd value of 2nd row
  5685. * @param initialM24 defines 4th value of 2nd row
  5686. * @param initialM31 defines 1st value of 3rd row
  5687. * @param initialM32 defines 2nd value of 3rd row
  5688. * @param initialM33 defines 3rd value of 3rd row
  5689. * @param initialM34 defines 4th value of 3rd row
  5690. * @param initialM41 defines 1st value of 4th row
  5691. * @param initialM42 defines 2nd value of 4th row
  5692. * @param initialM43 defines 3rd value of 4th row
  5693. * @param initialM44 defines 4th value of 4th row
  5694. * @returns the new matrix
  5695. */
  5696. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5697. var result = new Matrix();
  5698. result.m[0] = initialM11;
  5699. result.m[1] = initialM12;
  5700. result.m[2] = initialM13;
  5701. result.m[3] = initialM14;
  5702. result.m[4] = initialM21;
  5703. result.m[5] = initialM22;
  5704. result.m[6] = initialM23;
  5705. result.m[7] = initialM24;
  5706. result.m[8] = initialM31;
  5707. result.m[9] = initialM32;
  5708. result.m[10] = initialM33;
  5709. result.m[11] = initialM34;
  5710. result.m[12] = initialM41;
  5711. result.m[13] = initialM42;
  5712. result.m[14] = initialM43;
  5713. result.m[15] = initialM44;
  5714. return result;
  5715. };
  5716. /**
  5717. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5718. * @param scale defines the scale vector3
  5719. * @param rotation defines the rotation quaternion
  5720. * @param translation defines the translation vector3
  5721. * @returns a new matrix
  5722. */
  5723. Matrix.Compose = function (scale, rotation, translation) {
  5724. var result = Matrix.Identity();
  5725. Matrix.ComposeToRef(scale, rotation, translation, result);
  5726. return result;
  5727. };
  5728. /**
  5729. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5730. * @param scale defines the scale vector3
  5731. * @param rotation defines the rotation quaternion
  5732. * @param translation defines the translation vector3
  5733. * @param result defines the target matrix
  5734. */
  5735. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5736. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5737. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5738. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5739. result.setTranslation(translation);
  5740. };
  5741. /**
  5742. * Creates a new identity matrix
  5743. * @returns a new identity matrix
  5744. */
  5745. Matrix.Identity = function () {
  5746. 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);
  5747. };
  5748. /**
  5749. * Creates a new identity matrix and stores the result in a given matrix
  5750. * @param result defines the target matrix
  5751. */
  5752. Matrix.IdentityToRef = function (result) {
  5753. 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);
  5754. };
  5755. /**
  5756. * Creates a new zero matrix
  5757. * @returns a new zero matrix
  5758. */
  5759. Matrix.Zero = function () {
  5760. 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);
  5761. };
  5762. /**
  5763. * Creates a new rotation matrix for "angle" radians around the X axis
  5764. * @param angle defines the angle (in radians) to use
  5765. * @return the new matrix
  5766. */
  5767. Matrix.RotationX = function (angle) {
  5768. var result = new Matrix();
  5769. Matrix.RotationXToRef(angle, result);
  5770. return result;
  5771. };
  5772. /**
  5773. * Creates a new matrix as the invert of a given matrix
  5774. * @param source defines the source matrix
  5775. * @returns the new matrix
  5776. */
  5777. Matrix.Invert = function (source) {
  5778. var result = new Matrix();
  5779. source.invertToRef(result);
  5780. return result;
  5781. };
  5782. /**
  5783. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5784. * @param angle defines the angle (in radians) to use
  5785. * @param result defines the target matrix
  5786. */
  5787. Matrix.RotationXToRef = function (angle, result) {
  5788. var s = Math.sin(angle);
  5789. var c = Math.cos(angle);
  5790. result.m[0] = 1.0;
  5791. result.m[15] = 1.0;
  5792. result.m[5] = c;
  5793. result.m[10] = c;
  5794. result.m[9] = -s;
  5795. result.m[6] = s;
  5796. result.m[1] = 0.0;
  5797. result.m[2] = 0.0;
  5798. result.m[3] = 0.0;
  5799. result.m[4] = 0.0;
  5800. result.m[7] = 0.0;
  5801. result.m[8] = 0.0;
  5802. result.m[11] = 0.0;
  5803. result.m[12] = 0.0;
  5804. result.m[13] = 0.0;
  5805. result.m[14] = 0.0;
  5806. result._markAsUpdated();
  5807. };
  5808. /**
  5809. * Creates a new rotation matrix for "angle" radians around the Y axis
  5810. * @param angle defines the angle (in radians) to use
  5811. * @return the new matrix
  5812. */
  5813. Matrix.RotationY = function (angle) {
  5814. var result = new Matrix();
  5815. Matrix.RotationYToRef(angle, result);
  5816. return result;
  5817. };
  5818. /**
  5819. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5820. * @param angle defines the angle (in radians) to use
  5821. * @param result defines the target matrix
  5822. */
  5823. Matrix.RotationYToRef = function (angle, result) {
  5824. var s = Math.sin(angle);
  5825. var c = Math.cos(angle);
  5826. result.m[5] = 1.0;
  5827. result.m[15] = 1.0;
  5828. result.m[0] = c;
  5829. result.m[2] = -s;
  5830. result.m[8] = s;
  5831. result.m[10] = c;
  5832. result.m[1] = 0.0;
  5833. result.m[3] = 0.0;
  5834. result.m[4] = 0.0;
  5835. result.m[6] = 0.0;
  5836. result.m[7] = 0.0;
  5837. result.m[9] = 0.0;
  5838. result.m[11] = 0.0;
  5839. result.m[12] = 0.0;
  5840. result.m[13] = 0.0;
  5841. result.m[14] = 0.0;
  5842. result._markAsUpdated();
  5843. };
  5844. /**
  5845. * Creates a new rotation matrix for "angle" radians around the Z axis
  5846. * @param angle defines the angle (in radians) to use
  5847. * @return the new matrix
  5848. */
  5849. Matrix.RotationZ = function (angle) {
  5850. var result = new Matrix();
  5851. Matrix.RotationZToRef(angle, result);
  5852. return result;
  5853. };
  5854. /**
  5855. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5856. * @param angle defines the angle (in radians) to use
  5857. * @param result defines the target matrix
  5858. */
  5859. Matrix.RotationZToRef = function (angle, result) {
  5860. var s = Math.sin(angle);
  5861. var c = Math.cos(angle);
  5862. result.m[10] = 1.0;
  5863. result.m[15] = 1.0;
  5864. result.m[0] = c;
  5865. result.m[1] = s;
  5866. result.m[4] = -s;
  5867. result.m[5] = c;
  5868. result.m[2] = 0.0;
  5869. result.m[3] = 0.0;
  5870. result.m[6] = 0.0;
  5871. result.m[7] = 0.0;
  5872. result.m[8] = 0.0;
  5873. result.m[9] = 0.0;
  5874. result.m[11] = 0.0;
  5875. result.m[12] = 0.0;
  5876. result.m[13] = 0.0;
  5877. result.m[14] = 0.0;
  5878. result._markAsUpdated();
  5879. };
  5880. /**
  5881. * Creates a new rotation matrix for "angle" radians around the given axis
  5882. * @param axis defines the axis to use
  5883. * @param angle defines the angle (in radians) to use
  5884. * @return the new matrix
  5885. */
  5886. Matrix.RotationAxis = function (axis, angle) {
  5887. var result = Matrix.Zero();
  5888. Matrix.RotationAxisToRef(axis, angle, result);
  5889. return result;
  5890. };
  5891. /**
  5892. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5893. * @param axis defines the axis to use
  5894. * @param angle defines the angle (in radians) to use
  5895. * @param result defines the target matrix
  5896. */
  5897. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5898. var s = Math.sin(-angle);
  5899. var c = Math.cos(-angle);
  5900. var c1 = 1 - c;
  5901. axis.normalize();
  5902. result.m[0] = (axis.x * axis.x) * c1 + c;
  5903. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5904. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5905. result.m[3] = 0.0;
  5906. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5907. result.m[5] = (axis.y * axis.y) * c1 + c;
  5908. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5909. result.m[7] = 0.0;
  5910. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5911. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5912. result.m[10] = (axis.z * axis.z) * c1 + c;
  5913. result.m[11] = 0.0;
  5914. result.m[15] = 1.0;
  5915. result._markAsUpdated();
  5916. };
  5917. /**
  5918. * Creates a rotation matrix
  5919. * @param yaw defines the yaw angle in radians (Y axis)
  5920. * @param pitch defines the pitch angle in radians (X axis)
  5921. * @param roll defines the roll angle in radians (X axis)
  5922. * @returns the new rotation matrix
  5923. */
  5924. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5925. var result = new Matrix();
  5926. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5927. return result;
  5928. };
  5929. /**
  5930. * Creates a rotation matrix and stores it in a given matrix
  5931. * @param yaw defines the yaw angle in radians (Y axis)
  5932. * @param pitch defines the pitch angle in radians (X axis)
  5933. * @param roll defines the roll angle in radians (X axis)
  5934. * @param result defines the target matrix
  5935. */
  5936. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5937. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5938. this._tempQuaternion.toRotationMatrix(result);
  5939. };
  5940. /**
  5941. * Creates a scaling matrix
  5942. * @param x defines the scale factor on X axis
  5943. * @param y defines the scale factor on Y axis
  5944. * @param z defines the scale factor on Z axis
  5945. * @returns the new matrix
  5946. */
  5947. Matrix.Scaling = function (x, y, z) {
  5948. var result = Matrix.Zero();
  5949. Matrix.ScalingToRef(x, y, z, result);
  5950. return result;
  5951. };
  5952. /**
  5953. * Creates a scaling matrix and stores it in a given matrix
  5954. * @param x defines the scale factor on X axis
  5955. * @param y defines the scale factor on Y axis
  5956. * @param z defines the scale factor on Z axis
  5957. * @param result defines the target matrix
  5958. */
  5959. Matrix.ScalingToRef = function (x, y, z, result) {
  5960. result.m[0] = x;
  5961. result.m[1] = 0.0;
  5962. result.m[2] = 0.0;
  5963. result.m[3] = 0.0;
  5964. result.m[4] = 0.0;
  5965. result.m[5] = y;
  5966. result.m[6] = 0.0;
  5967. result.m[7] = 0.0;
  5968. result.m[8] = 0.0;
  5969. result.m[9] = 0.0;
  5970. result.m[10] = z;
  5971. result.m[11] = 0.0;
  5972. result.m[12] = 0.0;
  5973. result.m[13] = 0.0;
  5974. result.m[14] = 0.0;
  5975. result.m[15] = 1.0;
  5976. result._markAsUpdated();
  5977. };
  5978. /**
  5979. * Creates a translation matrix
  5980. * @param x defines the translation on X axis
  5981. * @param y defines the translation on Y axis
  5982. * @param z defines the translationon Z axis
  5983. * @returns the new matrix
  5984. */
  5985. Matrix.Translation = function (x, y, z) {
  5986. var result = Matrix.Identity();
  5987. Matrix.TranslationToRef(x, y, z, result);
  5988. return result;
  5989. };
  5990. /**
  5991. * Creates a translation matrix and stores it in a given matrix
  5992. * @param x defines the translation on X axis
  5993. * @param y defines the translation on Y axis
  5994. * @param z defines the translationon Z axis
  5995. * @param result defines the target matrix
  5996. */
  5997. Matrix.TranslationToRef = function (x, y, z, result) {
  5998. 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);
  5999. };
  6000. /**
  6001. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6002. * @param startValue defines the start value
  6003. * @param endValue defines the end value
  6004. * @param gradient defines the gradient factor
  6005. * @returns the new matrix
  6006. */
  6007. Matrix.Lerp = function (startValue, endValue, gradient) {
  6008. var result = Matrix.Zero();
  6009. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6010. return result;
  6011. };
  6012. /**
  6013. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6014. * @param startValue defines the start value
  6015. * @param endValue defines the end value
  6016. * @param gradient defines the gradient factor
  6017. * @param result defines the Matrix object where to store data
  6018. */
  6019. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6020. for (var index = 0; index < 16; index++) {
  6021. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6022. }
  6023. result._markAsUpdated();
  6024. };
  6025. /**
  6026. * Builds a new matrix whose values are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @returns the new matrix
  6034. */
  6035. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6036. var result = Matrix.Zero();
  6037. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6038. return result;
  6039. };
  6040. /**
  6041. * Update a matrix to values which are computed by:
  6042. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6043. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6044. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6045. * @param startValue defines the first matrix
  6046. * @param endValue defines the second matrix
  6047. * @param gradient defines the gradient between the two matrices
  6048. * @param result defines the target matrix
  6049. */
  6050. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6051. var startScale = MathTmp.Vector3[0];
  6052. var startRotation = MathTmp.Quaternion[0];
  6053. var startTranslation = MathTmp.Vector3[1];
  6054. startValue.decompose(startScale, startRotation, startTranslation);
  6055. var endScale = MathTmp.Vector3[2];
  6056. var endRotation = MathTmp.Quaternion[1];
  6057. var endTranslation = MathTmp.Vector3[3];
  6058. endValue.decompose(endScale, endRotation, endTranslation);
  6059. var resultScale = MathTmp.Vector3[4];
  6060. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6061. var resultRotation = MathTmp.Quaternion[2];
  6062. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6063. var resultTranslation = MathTmp.Vector3[5];
  6064. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6065. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6066. };
  6067. /**
  6068. * 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"
  6069. * This function works in left handed mode
  6070. * @param eye defines the final position of the entity
  6071. * @param target defines where the entity should look at
  6072. * @param up defines the up vector for the entity
  6073. * @returns the new matrix
  6074. */
  6075. Matrix.LookAtLH = function (eye, target, up) {
  6076. var result = Matrix.Zero();
  6077. Matrix.LookAtLHToRef(eye, target, up, result);
  6078. return result;
  6079. };
  6080. /**
  6081. * 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".
  6082. * This function works in left handed mode
  6083. * @param eye defines the final position of the entity
  6084. * @param target defines where the entity should look at
  6085. * @param up defines the up vector for the entity
  6086. * @param result defines the target matrix
  6087. */
  6088. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6089. // Z axis
  6090. target.subtractToRef(eye, this._zAxis);
  6091. this._zAxis.normalize();
  6092. // X axis
  6093. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6094. if (this._xAxis.lengthSquared() === 0) {
  6095. this._xAxis.x = 1.0;
  6096. }
  6097. else {
  6098. this._xAxis.normalize();
  6099. }
  6100. // Y axis
  6101. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6102. this._yAxis.normalize();
  6103. // Eye angles
  6104. var ex = -Vector3.Dot(this._xAxis, eye);
  6105. var ey = -Vector3.Dot(this._yAxis, eye);
  6106. var ez = -Vector3.Dot(this._zAxis, eye);
  6107. 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);
  6108. };
  6109. /**
  6110. * 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"
  6111. * This function works in right handed mode
  6112. * @param eye defines the final position of the entity
  6113. * @param target defines where the entity should look at
  6114. * @param up defines the up vector for the entity
  6115. * @returns the new matrix
  6116. */
  6117. Matrix.LookAtRH = function (eye, target, up) {
  6118. var result = Matrix.Zero();
  6119. Matrix.LookAtRHToRef(eye, target, up, result);
  6120. return result;
  6121. };
  6122. /**
  6123. * 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".
  6124. * This function works in right handed mode
  6125. * @param eye defines the final position of the entity
  6126. * @param target defines where the entity should look at
  6127. * @param up defines the up vector for the entity
  6128. * @param result defines the target matrix
  6129. */
  6130. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6131. // Z axis
  6132. eye.subtractToRef(target, this._zAxis);
  6133. this._zAxis.normalize();
  6134. // X axis
  6135. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6136. if (this._xAxis.lengthSquared() === 0) {
  6137. this._xAxis.x = 1.0;
  6138. }
  6139. else {
  6140. this._xAxis.normalize();
  6141. }
  6142. // Y axis
  6143. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6144. this._yAxis.normalize();
  6145. // Eye angles
  6146. var ex = -Vector3.Dot(this._xAxis, eye);
  6147. var ey = -Vector3.Dot(this._yAxis, eye);
  6148. var ez = -Vector3.Dot(this._zAxis, eye);
  6149. 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);
  6150. };
  6151. /**
  6152. * Create a left-handed orthographic projection matrix
  6153. * @param width defines the viewport width
  6154. * @param height defines the viewport height
  6155. * @param znear defines the near clip plane
  6156. * @param zfar defines the far clip plane
  6157. * @returns a new matrix as a left-handed orthographic projection matrix
  6158. */
  6159. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6160. var matrix = Matrix.Zero();
  6161. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6162. return matrix;
  6163. };
  6164. /**
  6165. * Store a left-handed orthographic projection to a given matrix
  6166. * @param width defines the viewport width
  6167. * @param height defines the viewport height
  6168. * @param znear defines the near clip plane
  6169. * @param zfar defines the far clip plane
  6170. * @param result defines the target matrix
  6171. */
  6172. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6173. var n = znear;
  6174. var f = zfar;
  6175. var a = 2.0 / width;
  6176. var b = 2.0 / height;
  6177. var c = 2.0 / (f - n);
  6178. var d = -(f + n) / (f - n);
  6179. 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);
  6180. };
  6181. /**
  6182. * Create a left-handed orthographic projection matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @returns a new matrix as a left-handed orthographic projection matrix
  6190. */
  6191. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6192. var matrix = Matrix.Zero();
  6193. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6194. return matrix;
  6195. };
  6196. /**
  6197. * Stores a left-handed orthographic projection into a given matrix
  6198. * @param left defines the viewport left coordinate
  6199. * @param right defines the viewport right coordinate
  6200. * @param bottom defines the viewport bottom coordinate
  6201. * @param top defines the viewport top coordinate
  6202. * @param znear defines the near clip plane
  6203. * @param zfar defines the far clip plane
  6204. * @param result defines the target matrix
  6205. */
  6206. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6207. var n = znear;
  6208. var f = zfar;
  6209. var a = 2.0 / (right - left);
  6210. var b = 2.0 / (top - bottom);
  6211. var c = 2.0 / (f - n);
  6212. var d = -(f + n) / (f - n);
  6213. var i0 = (left + right) / (left - right);
  6214. var i1 = (top + bottom) / (bottom - top);
  6215. 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);
  6216. };
  6217. /**
  6218. * Creates a right-handed orthographic projection matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @returns a new matrix as a right-handed orthographic projection matrix
  6226. */
  6227. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6228. var matrix = Matrix.Zero();
  6229. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6230. return matrix;
  6231. };
  6232. /**
  6233. * Stores a right-handed orthographic projection into a given matrix
  6234. * @param left defines the viewport left coordinate
  6235. * @param right defines the viewport right coordinate
  6236. * @param bottom defines the viewport bottom coordinate
  6237. * @param top defines the viewport top coordinate
  6238. * @param znear defines the near clip plane
  6239. * @param zfar defines the far clip plane
  6240. * @param result defines the target matrix
  6241. */
  6242. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6243. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6244. result.m[10] *= -1.0;
  6245. };
  6246. /**
  6247. * Creates a left-handed perspective projection matrix
  6248. * @param width defines the viewport width
  6249. * @param height defines the viewport height
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @returns a new matrix as a left-handed perspective projection matrix
  6253. */
  6254. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6255. var matrix = Matrix.Zero();
  6256. var n = znear;
  6257. var f = zfar;
  6258. var a = 2.0 * n / width;
  6259. var b = 2.0 * n / height;
  6260. var c = (f + n) / (f - n);
  6261. var d = -2.0 * f * n / (f - n);
  6262. 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);
  6263. return matrix;
  6264. };
  6265. /**
  6266. * Creates a left-handed perspective projection matrix
  6267. * @param fov defines the horizontal field of view
  6268. * @param aspect defines the aspect ratio
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @returns a new matrix as a left-handed perspective projection matrix
  6272. */
  6273. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6274. var matrix = Matrix.Zero();
  6275. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6276. return matrix;
  6277. };
  6278. /**
  6279. * Stores a left-handed perspective projection into a given matrix
  6280. * @param fov defines the horizontal field of view
  6281. * @param aspect defines the aspect ratio
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @param result defines the target matrix
  6285. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6286. */
  6287. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6288. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6289. var n = znear;
  6290. var f = zfar;
  6291. var t = 1.0 / (Math.tan(fov * 0.5));
  6292. var a = isVerticalFovFixed ? (t / aspect) : t;
  6293. var b = isVerticalFovFixed ? t : (t * aspect);
  6294. var c = (f + n) / (f - n);
  6295. var d = -2.0 * f * n / (f - n);
  6296. 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);
  6297. };
  6298. /**
  6299. * Creates a right-handed perspective projection matrix
  6300. * @param fov defines the horizontal field of view
  6301. * @param aspect defines the aspect ratio
  6302. * @param znear defines the near clip plane
  6303. * @param zfar defines the far clip plane
  6304. * @returns a new matrix as a right-handed perspective projection matrix
  6305. */
  6306. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6307. var matrix = Matrix.Zero();
  6308. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6309. return matrix;
  6310. };
  6311. /**
  6312. * Stores a right-handed perspective projection into a given matrix
  6313. * @param fov defines the horizontal field of view
  6314. * @param aspect defines the aspect ratio
  6315. * @param znear defines the near clip plane
  6316. * @param zfar defines the far clip plane
  6317. * @param result defines the target matrix
  6318. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6319. */
  6320. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6321. //alternatively this could be expressed as:
  6322. // m = PerspectiveFovLHToRef
  6323. // m[10] *= -1.0;
  6324. // m[11] *= -1.0;
  6325. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6326. var n = znear;
  6327. var f = zfar;
  6328. var t = 1.0 / (Math.tan(fov * 0.5));
  6329. var a = isVerticalFovFixed ? (t / aspect) : t;
  6330. var b = isVerticalFovFixed ? t : (t * aspect);
  6331. var c = -(f + n) / (f - n);
  6332. var d = -2 * f * n / (f - n);
  6333. 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);
  6334. };
  6335. /**
  6336. * Stores a perspective projection for WebVR info a given matrix
  6337. * @param fov defines the field of view
  6338. * @param znear defines the near clip plane
  6339. * @param zfar defines the far clip plane
  6340. * @param result defines the target matrix
  6341. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6342. */
  6343. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6344. if (rightHanded === void 0) { rightHanded = false; }
  6345. var rightHandedFactor = rightHanded ? -1 : 1;
  6346. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6347. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6348. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6349. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6350. var xScale = 2.0 / (leftTan + rightTan);
  6351. var yScale = 2.0 / (upTan + downTan);
  6352. result.m[0] = xScale;
  6353. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6354. result.m[5] = yScale;
  6355. result.m[6] = result.m[7] = 0.0;
  6356. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6357. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6358. result.m[10] = -zfar / (znear - zfar);
  6359. result.m[11] = 1.0 * rightHandedFactor;
  6360. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6361. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6362. result._markAsUpdated();
  6363. };
  6364. /**
  6365. * Computes a complete transformation matrix
  6366. * @param viewport defines the viewport to use
  6367. * @param world defines the world matrix
  6368. * @param view defines the view matrix
  6369. * @param projection defines the projection matrix
  6370. * @param zmin defines the near clip plane
  6371. * @param zmax defines the far clip plane
  6372. * @returns the transformation matrix
  6373. */
  6374. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6375. var cw = viewport.width;
  6376. var ch = viewport.height;
  6377. var cx = viewport.x;
  6378. var cy = viewport.y;
  6379. 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);
  6380. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6381. };
  6382. /**
  6383. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6384. * @param matrix defines the matrix to use
  6385. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6386. */
  6387. Matrix.GetAsMatrix2x2 = function (matrix) {
  6388. return new Float32Array([
  6389. matrix.m[0], matrix.m[1],
  6390. matrix.m[4], matrix.m[5]
  6391. ]);
  6392. };
  6393. /**
  6394. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6395. * @param matrix defines the matrix to use
  6396. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6397. */
  6398. Matrix.GetAsMatrix3x3 = function (matrix) {
  6399. return new Float32Array([
  6400. matrix.m[0], matrix.m[1], matrix.m[2],
  6401. matrix.m[4], matrix.m[5], matrix.m[6],
  6402. matrix.m[8], matrix.m[9], matrix.m[10]
  6403. ]);
  6404. };
  6405. /**
  6406. * Compute the transpose of a given matrix
  6407. * @param matrix defines the matrix to transpose
  6408. * @returns the new matrix
  6409. */
  6410. Matrix.Transpose = function (matrix) {
  6411. var result = new Matrix();
  6412. Matrix.TransposeToRef(matrix, result);
  6413. return result;
  6414. };
  6415. /**
  6416. * Compute the transpose of a matrix and store it in a target matrix
  6417. * @param matrix defines the matrix to transpose
  6418. * @param result defines the target matrix
  6419. */
  6420. Matrix.TransposeToRef = function (matrix, result) {
  6421. result.m[0] = matrix.m[0];
  6422. result.m[1] = matrix.m[4];
  6423. result.m[2] = matrix.m[8];
  6424. result.m[3] = matrix.m[12];
  6425. result.m[4] = matrix.m[1];
  6426. result.m[5] = matrix.m[5];
  6427. result.m[6] = matrix.m[9];
  6428. result.m[7] = matrix.m[13];
  6429. result.m[8] = matrix.m[2];
  6430. result.m[9] = matrix.m[6];
  6431. result.m[10] = matrix.m[10];
  6432. result.m[11] = matrix.m[14];
  6433. result.m[12] = matrix.m[3];
  6434. result.m[13] = matrix.m[7];
  6435. result.m[14] = matrix.m[11];
  6436. result.m[15] = matrix.m[15];
  6437. };
  6438. /**
  6439. * Computes a reflection matrix from a plane
  6440. * @param plane defines the reflection plane
  6441. * @returns a new matrix
  6442. */
  6443. Matrix.Reflection = function (plane) {
  6444. var matrix = new Matrix();
  6445. Matrix.ReflectionToRef(plane, matrix);
  6446. return matrix;
  6447. };
  6448. /**
  6449. * Computes a reflection matrix from a plane
  6450. * @param plane defines the reflection plane
  6451. * @param result defines the target matrix
  6452. */
  6453. Matrix.ReflectionToRef = function (plane, result) {
  6454. plane.normalize();
  6455. var x = plane.normal.x;
  6456. var y = plane.normal.y;
  6457. var z = plane.normal.z;
  6458. var temp = -2 * x;
  6459. var temp2 = -2 * y;
  6460. var temp3 = -2 * z;
  6461. result.m[0] = (temp * x) + 1;
  6462. result.m[1] = temp2 * x;
  6463. result.m[2] = temp3 * x;
  6464. result.m[3] = 0.0;
  6465. result.m[4] = temp * y;
  6466. result.m[5] = (temp2 * y) + 1;
  6467. result.m[6] = temp3 * y;
  6468. result.m[7] = 0.0;
  6469. result.m[8] = temp * z;
  6470. result.m[9] = temp2 * z;
  6471. result.m[10] = (temp3 * z) + 1;
  6472. result.m[11] = 0.0;
  6473. result.m[12] = temp * plane.d;
  6474. result.m[13] = temp2 * plane.d;
  6475. result.m[14] = temp3 * plane.d;
  6476. result.m[15] = 1.0;
  6477. result._markAsUpdated();
  6478. };
  6479. /**
  6480. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6481. * @param xaxis defines the value of the 1st axis
  6482. * @param yaxis defines the value of the 2nd axis
  6483. * @param zaxis defines the value of the 3rd axis
  6484. * @param result defines the target matrix
  6485. */
  6486. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6487. result.m[0] = xaxis.x;
  6488. result.m[1] = xaxis.y;
  6489. result.m[2] = xaxis.z;
  6490. result.m[3] = 0.0;
  6491. result.m[4] = yaxis.x;
  6492. result.m[5] = yaxis.y;
  6493. result.m[6] = yaxis.z;
  6494. result.m[7] = 0.0;
  6495. result.m[8] = zaxis.x;
  6496. result.m[9] = zaxis.y;
  6497. result.m[10] = zaxis.z;
  6498. result.m[11] = 0.0;
  6499. result.m[12] = 0.0;
  6500. result.m[13] = 0.0;
  6501. result.m[14] = 0.0;
  6502. result.m[15] = 1.0;
  6503. result._markAsUpdated();
  6504. };
  6505. /**
  6506. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6507. * @param quat defines the quaternion to use
  6508. * @param result defines the target matrix
  6509. */
  6510. Matrix.FromQuaternionToRef = function (quat, result) {
  6511. var xx = quat.x * quat.x;
  6512. var yy = quat.y * quat.y;
  6513. var zz = quat.z * quat.z;
  6514. var xy = quat.x * quat.y;
  6515. var zw = quat.z * quat.w;
  6516. var zx = quat.z * quat.x;
  6517. var yw = quat.y * quat.w;
  6518. var yz = quat.y * quat.z;
  6519. var xw = quat.x * quat.w;
  6520. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6521. result.m[1] = 2.0 * (xy + zw);
  6522. result.m[2] = 2.0 * (zx - yw);
  6523. result.m[3] = 0.0;
  6524. result.m[4] = 2.0 * (xy - zw);
  6525. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6526. result.m[6] = 2.0 * (yz + xw);
  6527. result.m[7] = 0.0;
  6528. result.m[8] = 2.0 * (zx + yw);
  6529. result.m[9] = 2.0 * (yz - xw);
  6530. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6531. result.m[11] = 0.0;
  6532. result.m[12] = 0.0;
  6533. result.m[13] = 0.0;
  6534. result.m[14] = 0.0;
  6535. result.m[15] = 1.0;
  6536. result._markAsUpdated();
  6537. };
  6538. Matrix._tempQuaternion = new Quaternion();
  6539. Matrix._xAxis = Vector3.Zero();
  6540. Matrix._yAxis = Vector3.Zero();
  6541. Matrix._zAxis = Vector3.Zero();
  6542. Matrix._updateFlagSeed = 0;
  6543. Matrix._identityReadOnly = Matrix.Identity();
  6544. return Matrix;
  6545. }());
  6546. BABYLON.Matrix = Matrix;
  6547. var Plane = /** @class */ (function () {
  6548. /**
  6549. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6550. */
  6551. function Plane(a, b, c, d) {
  6552. this.normal = new Vector3(a, b, c);
  6553. this.d = d;
  6554. }
  6555. /**
  6556. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6557. */
  6558. Plane.prototype.asArray = function () {
  6559. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6560. };
  6561. // Methods
  6562. /**
  6563. * Returns a new plane copied from the current Plane.
  6564. */
  6565. Plane.prototype.clone = function () {
  6566. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6567. };
  6568. /**
  6569. * Returns the string "Plane".
  6570. */
  6571. Plane.prototype.getClassName = function () {
  6572. return "Plane";
  6573. };
  6574. /**
  6575. * Returns the Plane hash code.
  6576. */
  6577. Plane.prototype.getHashCode = function () {
  6578. var hash = this.normal.getHashCode();
  6579. hash = (hash * 397) ^ (this.d || 0);
  6580. return hash;
  6581. };
  6582. /**
  6583. * Normalize the current Plane in place.
  6584. * Returns the updated Plane.
  6585. */
  6586. Plane.prototype.normalize = function () {
  6587. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6588. var magnitude = 0.0;
  6589. if (norm !== 0) {
  6590. magnitude = 1.0 / norm;
  6591. }
  6592. this.normal.x *= magnitude;
  6593. this.normal.y *= magnitude;
  6594. this.normal.z *= magnitude;
  6595. this.d *= magnitude;
  6596. return this;
  6597. };
  6598. /**
  6599. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6600. */
  6601. Plane.prototype.transform = function (transformation) {
  6602. var transposedMatrix = Matrix.Transpose(transformation);
  6603. var x = this.normal.x;
  6604. var y = this.normal.y;
  6605. var z = this.normal.z;
  6606. var d = this.d;
  6607. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6608. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6609. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6610. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6611. return new Plane(normalX, normalY, normalZ, finalD);
  6612. };
  6613. /**
  6614. * Returns the dot product (float) of the point coordinates and the plane normal.
  6615. */
  6616. Plane.prototype.dotCoordinate = function (point) {
  6617. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6618. };
  6619. /**
  6620. * Updates the current Plane from the plane defined by the three given points.
  6621. * Returns the updated Plane.
  6622. */
  6623. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6624. var x1 = point2.x - point1.x;
  6625. var y1 = point2.y - point1.y;
  6626. var z1 = point2.z - point1.z;
  6627. var x2 = point3.x - point1.x;
  6628. var y2 = point3.y - point1.y;
  6629. var z2 = point3.z - point1.z;
  6630. var yz = (y1 * z2) - (z1 * y2);
  6631. var xz = (z1 * x2) - (x1 * z2);
  6632. var xy = (x1 * y2) - (y1 * x2);
  6633. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6634. var invPyth;
  6635. if (pyth !== 0) {
  6636. invPyth = 1.0 / pyth;
  6637. }
  6638. else {
  6639. invPyth = 0.0;
  6640. }
  6641. this.normal.x = yz * invPyth;
  6642. this.normal.y = xz * invPyth;
  6643. this.normal.z = xy * invPyth;
  6644. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6645. return this;
  6646. };
  6647. /**
  6648. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6649. */
  6650. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6651. var dot = Vector3.Dot(this.normal, direction);
  6652. return (dot <= epsilon);
  6653. };
  6654. /**
  6655. * Returns the signed distance (float) from the given point to the Plane.
  6656. */
  6657. Plane.prototype.signedDistanceTo = function (point) {
  6658. return Vector3.Dot(point, this.normal) + this.d;
  6659. };
  6660. // Statics
  6661. /**
  6662. * Returns a new Plane from the given array.
  6663. */
  6664. Plane.FromArray = function (array) {
  6665. return new Plane(array[0], array[1], array[2], array[3]);
  6666. };
  6667. /**
  6668. * Returns a new Plane defined by the three given points.
  6669. */
  6670. Plane.FromPoints = function (point1, point2, point3) {
  6671. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6672. result.copyFromPoints(point1, point2, point3);
  6673. return result;
  6674. };
  6675. /**
  6676. * Returns a new Plane the normal vector to this plane at the given origin point.
  6677. * Note : the vector "normal" is updated because normalized.
  6678. */
  6679. Plane.FromPositionAndNormal = function (origin, normal) {
  6680. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6681. normal.normalize();
  6682. result.normal = normal;
  6683. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6684. return result;
  6685. };
  6686. /**
  6687. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6688. */
  6689. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6690. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6691. return Vector3.Dot(point, normal) + d;
  6692. };
  6693. return Plane;
  6694. }());
  6695. BABYLON.Plane = Plane;
  6696. var Viewport = /** @class */ (function () {
  6697. /**
  6698. * Creates a Viewport object located at (x, y) and sized (width, height).
  6699. */
  6700. function Viewport(x, y, width, height) {
  6701. this.x = x;
  6702. this.y = y;
  6703. this.width = width;
  6704. this.height = height;
  6705. }
  6706. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6707. if (renderWidthOrEngine.getRenderWidth) {
  6708. var engine = renderWidthOrEngine;
  6709. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6710. }
  6711. var renderWidth = renderWidthOrEngine;
  6712. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6713. };
  6714. /**
  6715. * Returns a new Viewport copied from the current one.
  6716. */
  6717. Viewport.prototype.clone = function () {
  6718. return new Viewport(this.x, this.y, this.width, this.height);
  6719. };
  6720. return Viewport;
  6721. }());
  6722. BABYLON.Viewport = Viewport;
  6723. var Frustum = /** @class */ (function () {
  6724. function Frustum() {
  6725. }
  6726. /**
  6727. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6728. */
  6729. Frustum.GetPlanes = function (transform) {
  6730. var frustumPlanes = [];
  6731. for (var index = 0; index < 6; index++) {
  6732. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6733. }
  6734. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6735. return frustumPlanes;
  6736. };
  6737. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6738. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6739. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6740. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6741. frustumPlane.d = transform.m[15] + transform.m[14];
  6742. frustumPlane.normalize();
  6743. };
  6744. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6745. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6746. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6747. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6748. frustumPlane.d = transform.m[15] - transform.m[14];
  6749. frustumPlane.normalize();
  6750. };
  6751. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6752. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6753. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6754. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6755. frustumPlane.d = transform.m[15] + transform.m[12];
  6756. frustumPlane.normalize();
  6757. };
  6758. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6759. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6760. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6761. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6762. frustumPlane.d = transform.m[15] - transform.m[12];
  6763. frustumPlane.normalize();
  6764. };
  6765. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6766. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6767. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6768. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6769. frustumPlane.d = transform.m[15] - transform.m[13];
  6770. frustumPlane.normalize();
  6771. };
  6772. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6773. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6774. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6775. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6776. frustumPlane.d = transform.m[15] + transform.m[13];
  6777. frustumPlane.normalize();
  6778. };
  6779. /**
  6780. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6781. */
  6782. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6783. // Near
  6784. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6785. // Far
  6786. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6787. // Left
  6788. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6789. // Right
  6790. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6791. // Top
  6792. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6793. // Bottom
  6794. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6795. };
  6796. return Frustum;
  6797. }());
  6798. BABYLON.Frustum = Frustum;
  6799. /** Defines supported spaces */
  6800. var Space;
  6801. (function (Space) {
  6802. /** Local (object) space */
  6803. Space[Space["LOCAL"] = 0] = "LOCAL";
  6804. /** World space */
  6805. Space[Space["WORLD"] = 1] = "WORLD";
  6806. /** Bone space */
  6807. Space[Space["BONE"] = 2] = "BONE";
  6808. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6809. /** Defines the 3 main axes */
  6810. var Axis = /** @class */ (function () {
  6811. function Axis() {
  6812. }
  6813. /** X axis */
  6814. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6815. /** Y axis */
  6816. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6817. /** Z axis */
  6818. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6819. return Axis;
  6820. }());
  6821. BABYLON.Axis = Axis;
  6822. ;
  6823. var BezierCurve = /** @class */ (function () {
  6824. function BezierCurve() {
  6825. }
  6826. /**
  6827. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6828. */
  6829. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6830. // Extract X (which is equal to time here)
  6831. var f0 = 1 - 3 * x2 + 3 * x1;
  6832. var f1 = 3 * x2 - 6 * x1;
  6833. var f2 = 3 * x1;
  6834. var refinedT = t;
  6835. for (var i = 0; i < 5; i++) {
  6836. var refinedT2 = refinedT * refinedT;
  6837. var refinedT3 = refinedT2 * refinedT;
  6838. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6839. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6840. refinedT -= (x - t) * slope;
  6841. refinedT = Math.min(1, Math.max(0, refinedT));
  6842. }
  6843. // Resolve cubic bezier for the given x
  6844. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6845. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6846. Math.pow(refinedT, 3);
  6847. };
  6848. return BezierCurve;
  6849. }());
  6850. BABYLON.BezierCurve = BezierCurve;
  6851. /**
  6852. * Defines potential orientation for back face culling
  6853. */
  6854. var Orientation;
  6855. (function (Orientation) {
  6856. /**
  6857. * Clockwise
  6858. */
  6859. Orientation[Orientation["CW"] = 0] = "CW";
  6860. /** Counter clockwise */
  6861. Orientation[Orientation["CCW"] = 1] = "CCW";
  6862. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6863. /**
  6864. * Defines angle representation
  6865. */
  6866. var Angle = /** @class */ (function () {
  6867. /**
  6868. * Creates an Angle object of "radians" radians (float).
  6869. */
  6870. function Angle(radians) {
  6871. this._radians = radians;
  6872. if (this._radians < 0.0)
  6873. this._radians += (2.0 * Math.PI);
  6874. }
  6875. /**
  6876. * Get value in degrees
  6877. * @returns the Angle value in degrees (float)
  6878. */
  6879. Angle.prototype.degrees = function () {
  6880. return this._radians * 180.0 / Math.PI;
  6881. };
  6882. /**
  6883. * Get value in radians
  6884. * @returns the Angle value in radians (float)
  6885. */
  6886. Angle.prototype.radians = function () {
  6887. return this._radians;
  6888. };
  6889. /**
  6890. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6891. * @param a defines first vector
  6892. * @param b defines second vector
  6893. * @returns a new Angle
  6894. */
  6895. Angle.BetweenTwoPoints = function (a, b) {
  6896. var delta = b.subtract(a);
  6897. var theta = Math.atan2(delta.y, delta.x);
  6898. return new Angle(theta);
  6899. };
  6900. /**
  6901. * Gets a new Angle object from the given float in radians
  6902. * @param radians defines the angle value in radians
  6903. * @returns a new Angle
  6904. */
  6905. Angle.FromRadians = function (radians) {
  6906. return new Angle(radians);
  6907. };
  6908. /**
  6909. * Gets a new Angle object from the given float in degrees
  6910. * @param degrees defines the angle value in degrees
  6911. * @returns a new Angle
  6912. */
  6913. Angle.FromDegrees = function (degrees) {
  6914. return new Angle(degrees * Math.PI / 180.0);
  6915. };
  6916. return Angle;
  6917. }());
  6918. BABYLON.Angle = Angle;
  6919. var Arc2 = /** @class */ (function () {
  6920. /**
  6921. * Creates an Arc object from the three given points : start, middle and end.
  6922. */
  6923. function Arc2(startPoint, midPoint, endPoint) {
  6924. this.startPoint = startPoint;
  6925. this.midPoint = midPoint;
  6926. this.endPoint = endPoint;
  6927. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6928. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6929. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6930. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6931. 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);
  6932. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6933. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6934. var a1 = this.startAngle.degrees();
  6935. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6936. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6937. // angles correction
  6938. if (a2 - a1 > +180.0)
  6939. a2 -= 360.0;
  6940. if (a2 - a1 < -180.0)
  6941. a2 += 360.0;
  6942. if (a3 - a2 > +180.0)
  6943. a3 -= 360.0;
  6944. if (a3 - a2 < -180.0)
  6945. a3 += 360.0;
  6946. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6947. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6948. }
  6949. return Arc2;
  6950. }());
  6951. BABYLON.Arc2 = Arc2;
  6952. var Path2 = /** @class */ (function () {
  6953. /**
  6954. * Creates a Path2 object from the starting 2D coordinates x and y.
  6955. */
  6956. function Path2(x, y) {
  6957. this._points = new Array();
  6958. this._length = 0.0;
  6959. this.closed = false;
  6960. this._points.push(new Vector2(x, y));
  6961. }
  6962. /**
  6963. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6964. * Returns the updated Path2.
  6965. */
  6966. Path2.prototype.addLineTo = function (x, y) {
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var newPoint = new Vector2(x, y);
  6971. var previousPoint = this._points[this._points.length - 1];
  6972. this._points.push(newPoint);
  6973. this._length += newPoint.subtract(previousPoint).length();
  6974. return this;
  6975. };
  6976. /**
  6977. * 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.
  6978. * Returns the updated Path2.
  6979. */
  6980. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6981. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6982. if (this.closed) {
  6983. return this;
  6984. }
  6985. var startPoint = this._points[this._points.length - 1];
  6986. var midPoint = new Vector2(midX, midY);
  6987. var endPoint = new Vector2(endX, endY);
  6988. var arc = new Arc2(startPoint, midPoint, endPoint);
  6989. var increment = arc.angle.radians() / numberOfSegments;
  6990. if (arc.orientation === Orientation.CW)
  6991. increment *= -1;
  6992. var currentAngle = arc.startAngle.radians() + increment;
  6993. for (var i = 0; i < numberOfSegments; i++) {
  6994. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6995. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6996. this.addLineTo(x, y);
  6997. currentAngle += increment;
  6998. }
  6999. return this;
  7000. };
  7001. /**
  7002. * Closes the Path2.
  7003. * Returns the Path2.
  7004. */
  7005. Path2.prototype.close = function () {
  7006. this.closed = true;
  7007. return this;
  7008. };
  7009. /**
  7010. * Returns the Path2 total length (float).
  7011. */
  7012. Path2.prototype.length = function () {
  7013. var result = this._length;
  7014. if (!this.closed) {
  7015. var lastPoint = this._points[this._points.length - 1];
  7016. var firstPoint = this._points[0];
  7017. result += (firstPoint.subtract(lastPoint).length());
  7018. }
  7019. return result;
  7020. };
  7021. /**
  7022. * Returns the Path2 internal array of points.
  7023. */
  7024. Path2.prototype.getPoints = function () {
  7025. return this._points;
  7026. };
  7027. /**
  7028. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7029. */
  7030. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7031. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7032. return Vector2.Zero();
  7033. }
  7034. var lengthPosition = normalizedLengthPosition * this.length();
  7035. var previousOffset = 0;
  7036. for (var i = 0; i < this._points.length; i++) {
  7037. var j = (i + 1) % this._points.length;
  7038. var a = this._points[i];
  7039. var b = this._points[j];
  7040. var bToA = b.subtract(a);
  7041. var nextOffset = (bToA.length() + previousOffset);
  7042. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7043. var dir = bToA.normalize();
  7044. var localOffset = lengthPosition - previousOffset;
  7045. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7046. }
  7047. previousOffset = nextOffset;
  7048. }
  7049. return Vector2.Zero();
  7050. };
  7051. /**
  7052. * Returns a new Path2 starting at the coordinates (x, y).
  7053. */
  7054. Path2.StartingAt = function (x, y) {
  7055. return new Path2(x, y);
  7056. };
  7057. return Path2;
  7058. }());
  7059. BABYLON.Path2 = Path2;
  7060. var Path3D = /** @class */ (function () {
  7061. /**
  7062. * new Path3D(path, normal, raw)
  7063. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7064. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7065. * path : an array of Vector3, the curve axis of the Path3D
  7066. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7067. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7068. */
  7069. function Path3D(path, firstNormal, raw) {
  7070. if (firstNormal === void 0) { firstNormal = null; }
  7071. this.path = path;
  7072. this._curve = new Array();
  7073. this._distances = new Array();
  7074. this._tangents = new Array();
  7075. this._normals = new Array();
  7076. this._binormals = new Array();
  7077. for (var p = 0; p < path.length; p++) {
  7078. this._curve[p] = path[p].clone(); // hard copy
  7079. }
  7080. this._raw = raw || false;
  7081. this._compute(firstNormal);
  7082. }
  7083. /**
  7084. * Returns the Path3D array of successive Vector3 designing its curve.
  7085. */
  7086. Path3D.prototype.getCurve = function () {
  7087. return this._curve;
  7088. };
  7089. /**
  7090. * Returns an array populated with tangent vectors on each Path3D curve point.
  7091. */
  7092. Path3D.prototype.getTangents = function () {
  7093. return this._tangents;
  7094. };
  7095. /**
  7096. * Returns an array populated with normal vectors on each Path3D curve point.
  7097. */
  7098. Path3D.prototype.getNormals = function () {
  7099. return this._normals;
  7100. };
  7101. /**
  7102. * Returns an array populated with binormal vectors on each Path3D curve point.
  7103. */
  7104. Path3D.prototype.getBinormals = function () {
  7105. return this._binormals;
  7106. };
  7107. /**
  7108. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7109. */
  7110. Path3D.prototype.getDistances = function () {
  7111. return this._distances;
  7112. };
  7113. /**
  7114. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7115. * Returns the same object updated.
  7116. */
  7117. Path3D.prototype.update = function (path, firstNormal) {
  7118. if (firstNormal === void 0) { firstNormal = null; }
  7119. for (var p = 0; p < path.length; p++) {
  7120. this._curve[p].x = path[p].x;
  7121. this._curve[p].y = path[p].y;
  7122. this._curve[p].z = path[p].z;
  7123. }
  7124. this._compute(firstNormal);
  7125. return this;
  7126. };
  7127. // private function compute() : computes tangents, normals and binormals
  7128. Path3D.prototype._compute = function (firstNormal) {
  7129. var l = this._curve.length;
  7130. // first and last tangents
  7131. this._tangents[0] = this._getFirstNonNullVector(0);
  7132. if (!this._raw) {
  7133. this._tangents[0].normalize();
  7134. }
  7135. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7136. if (!this._raw) {
  7137. this._tangents[l - 1].normalize();
  7138. }
  7139. // normals and binormals at first point : arbitrary vector with _normalVector()
  7140. var tg0 = this._tangents[0];
  7141. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7142. this._normals[0] = pp0;
  7143. if (!this._raw) {
  7144. this._normals[0].normalize();
  7145. }
  7146. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7147. if (!this._raw) {
  7148. this._binormals[0].normalize();
  7149. }
  7150. this._distances[0] = 0.0;
  7151. // normals and binormals : next points
  7152. var prev; // previous vector (segment)
  7153. var cur; // current vector (segment)
  7154. var curTang; // current tangent
  7155. // previous normal
  7156. var prevBinor; // previous binormal
  7157. for (var i = 1; i < l; i++) {
  7158. // tangents
  7159. prev = this._getLastNonNullVector(i);
  7160. if (i < l - 1) {
  7161. cur = this._getFirstNonNullVector(i);
  7162. this._tangents[i] = prev.add(cur);
  7163. this._tangents[i].normalize();
  7164. }
  7165. this._distances[i] = this._distances[i - 1] + prev.length();
  7166. // normals and binormals
  7167. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7168. curTang = this._tangents[i];
  7169. prevBinor = this._binormals[i - 1];
  7170. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7171. if (!this._raw) {
  7172. this._normals[i].normalize();
  7173. }
  7174. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7175. if (!this._raw) {
  7176. this._binormals[i].normalize();
  7177. }
  7178. }
  7179. };
  7180. // private function getFirstNonNullVector(index)
  7181. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7182. Path3D.prototype._getFirstNonNullVector = function (index) {
  7183. var i = 1;
  7184. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7185. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7186. i++;
  7187. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7188. }
  7189. return nNVector;
  7190. };
  7191. // private function getLastNonNullVector(index)
  7192. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7193. Path3D.prototype._getLastNonNullVector = function (index) {
  7194. var i = 1;
  7195. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7196. while (nLVector.length() === 0 && index > i + 1) {
  7197. i++;
  7198. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7199. }
  7200. return nLVector;
  7201. };
  7202. // private function normalVector(v0, vt, va) :
  7203. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7204. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7205. Path3D.prototype._normalVector = function (v0, vt, va) {
  7206. var normal0;
  7207. var tgl = vt.length();
  7208. if (tgl === 0.0) {
  7209. tgl = 1.0;
  7210. }
  7211. if (va === undefined || va === null) {
  7212. var point;
  7213. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7214. point = new Vector3(0.0, -1.0, 0.0);
  7215. }
  7216. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7217. point = new Vector3(1.0, 0.0, 0.0);
  7218. }
  7219. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7220. point = new Vector3(0.0, 0.0, 1.0);
  7221. }
  7222. else {
  7223. point = Vector3.Zero();
  7224. }
  7225. normal0 = Vector3.Cross(vt, point);
  7226. }
  7227. else {
  7228. normal0 = Vector3.Cross(vt, va);
  7229. Vector3.CrossToRef(normal0, vt, normal0);
  7230. }
  7231. normal0.normalize();
  7232. return normal0;
  7233. };
  7234. return Path3D;
  7235. }());
  7236. BABYLON.Path3D = Path3D;
  7237. var Curve3 = /** @class */ (function () {
  7238. /**
  7239. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7240. * A Curve3 is designed from a series of successive Vector3.
  7241. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7242. */
  7243. function Curve3(points) {
  7244. this._length = 0.0;
  7245. this._points = points;
  7246. this._length = this._computeLength(points);
  7247. }
  7248. /**
  7249. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7250. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7251. * @param v1 (Vector3) the control point
  7252. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7253. * @param nbPoints (integer) the wanted number of points in the curve
  7254. */
  7255. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7256. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7257. var bez = new Array();
  7258. var equation = function (t, val0, val1, val2) {
  7259. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7260. return res;
  7261. };
  7262. for (var i = 0; i <= nbPoints; i++) {
  7263. 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)));
  7264. }
  7265. return new Curve3(bez);
  7266. };
  7267. /**
  7268. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7269. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7270. * @param v1 (Vector3) the first control point
  7271. * @param v2 (Vector3) the second control point
  7272. * @param v3 (Vector3) the end point of the Cubic Bezier
  7273. * @param nbPoints (integer) the wanted number of points in the curve
  7274. */
  7275. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7276. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7277. var bez = new Array();
  7278. var equation = function (t, val0, val1, val2, val3) {
  7279. 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;
  7280. return res;
  7281. };
  7282. for (var i = 0; i <= nbPoints; i++) {
  7283. 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)));
  7284. }
  7285. return new Curve3(bez);
  7286. };
  7287. /**
  7288. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7289. * @param p1 (Vector3) the origin point of the Hermite Spline
  7290. * @param t1 (Vector3) the tangent vector at the origin point
  7291. * @param p2 (Vector3) the end point of the Hermite Spline
  7292. * @param t2 (Vector3) the tangent vector at the end point
  7293. * @param nbPoints (integer) the wanted number of points in the curve
  7294. */
  7295. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7296. var hermite = new Array();
  7297. var step = 1.0 / nbPoints;
  7298. for (var i = 0; i <= nbPoints; i++) {
  7299. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7300. }
  7301. return new Curve3(hermite);
  7302. };
  7303. /**
  7304. * Returns a Curve3 object along a CatmullRom Spline curve :
  7305. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7306. * @param nbPoints (integer) the wanted number of points between each curve control points
  7307. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7308. */
  7309. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7310. var catmullRom = new Array();
  7311. var step = 1.0 / nbPoints;
  7312. var amount = 0.0;
  7313. if (closed) {
  7314. var pointsCount = points.length;
  7315. for (var i = 0; i < pointsCount; i++) {
  7316. amount = 0;
  7317. for (var c = 0; c < nbPoints; c++) {
  7318. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7319. amount += step;
  7320. }
  7321. }
  7322. catmullRom.push(catmullRom[0]);
  7323. }
  7324. else {
  7325. var totalPoints = new Array();
  7326. totalPoints.push(points[0].clone());
  7327. Array.prototype.push.apply(totalPoints, points);
  7328. totalPoints.push(points[points.length - 1].clone());
  7329. for (var i = 0; i < totalPoints.length - 3; i++) {
  7330. amount = 0;
  7331. for (var c = 0; c < nbPoints; c++) {
  7332. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7333. amount += step;
  7334. }
  7335. }
  7336. i--;
  7337. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7338. }
  7339. return new Curve3(catmullRom);
  7340. };
  7341. /**
  7342. * Returns the Curve3 stored array of successive Vector3
  7343. */
  7344. Curve3.prototype.getPoints = function () {
  7345. return this._points;
  7346. };
  7347. /**
  7348. * Returns the computed length (float) of the curve.
  7349. */
  7350. Curve3.prototype.length = function () {
  7351. return this._length;
  7352. };
  7353. /**
  7354. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7355. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7356. * curveA and curveB keep unchanged.
  7357. */
  7358. Curve3.prototype.continue = function (curve) {
  7359. var lastPoint = this._points[this._points.length - 1];
  7360. var continuedPoints = this._points.slice();
  7361. var curvePoints = curve.getPoints();
  7362. for (var i = 1; i < curvePoints.length; i++) {
  7363. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7364. }
  7365. var continuedCurve = new Curve3(continuedPoints);
  7366. return continuedCurve;
  7367. };
  7368. Curve3.prototype._computeLength = function (path) {
  7369. var l = 0;
  7370. for (var i = 1; i < path.length; i++) {
  7371. l += (path[i].subtract(path[i - 1])).length();
  7372. }
  7373. return l;
  7374. };
  7375. return Curve3;
  7376. }());
  7377. BABYLON.Curve3 = Curve3;
  7378. // Vertex formats
  7379. var PositionNormalVertex = /** @class */ (function () {
  7380. function PositionNormalVertex(position, normal) {
  7381. if (position === void 0) { position = Vector3.Zero(); }
  7382. if (normal === void 0) { normal = Vector3.Up(); }
  7383. this.position = position;
  7384. this.normal = normal;
  7385. }
  7386. PositionNormalVertex.prototype.clone = function () {
  7387. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7388. };
  7389. return PositionNormalVertex;
  7390. }());
  7391. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7392. var PositionNormalTextureVertex = /** @class */ (function () {
  7393. function PositionNormalTextureVertex(position, normal, uv) {
  7394. if (position === void 0) { position = Vector3.Zero(); }
  7395. if (normal === void 0) { normal = Vector3.Up(); }
  7396. if (uv === void 0) { uv = Vector2.Zero(); }
  7397. this.position = position;
  7398. this.normal = normal;
  7399. this.uv = uv;
  7400. }
  7401. PositionNormalTextureVertex.prototype.clone = function () {
  7402. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7403. };
  7404. return PositionNormalTextureVertex;
  7405. }());
  7406. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7407. // Temporary pre-allocated objects for engine internal use
  7408. // usage in any internal function :
  7409. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7410. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7411. var Tmp = /** @class */ (function () {
  7412. function Tmp() {
  7413. }
  7414. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7415. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7416. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7417. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7418. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7419. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7420. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7421. Matrix.Zero(), Matrix.Zero(),
  7422. Matrix.Zero(), Matrix.Zero(),
  7423. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7424. return Tmp;
  7425. }());
  7426. BABYLON.Tmp = Tmp;
  7427. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7428. var MathTmp = /** @class */ (function () {
  7429. function MathTmp() {
  7430. }
  7431. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7432. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7433. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7434. return MathTmp;
  7435. }());
  7436. })(BABYLON || (BABYLON = {}));
  7437. //# sourceMappingURL=babylon.math.js.map
  7438. var BABYLON;
  7439. (function (BABYLON) {
  7440. var Scalar = /** @class */ (function () {
  7441. function Scalar() {
  7442. }
  7443. /**
  7444. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7445. */
  7446. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7447. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7448. var num = a - b;
  7449. return -epsilon <= num && num <= epsilon;
  7450. };
  7451. /**
  7452. * Returns a string : the upper case translation of the number i to hexadecimal.
  7453. */
  7454. Scalar.ToHex = function (i) {
  7455. var str = i.toString(16);
  7456. if (i <= 15) {
  7457. return ("0" + str).toUpperCase();
  7458. }
  7459. return str.toUpperCase();
  7460. };
  7461. /**
  7462. * Returns -1 if value is negative and +1 is value is positive.
  7463. * Returns the value itself if it's equal to zero.
  7464. */
  7465. Scalar.Sign = function (value) {
  7466. value = +value; // convert to a number
  7467. if (value === 0 || isNaN(value))
  7468. return value;
  7469. return value > 0 ? 1 : -1;
  7470. };
  7471. /**
  7472. * Returns the value itself if it's between min and max.
  7473. * Returns min if the value is lower than min.
  7474. * Returns max if the value is greater than max.
  7475. */
  7476. Scalar.Clamp = function (value, min, max) {
  7477. if (min === void 0) { min = 0; }
  7478. if (max === void 0) { max = 1; }
  7479. return Math.min(max, Math.max(min, value));
  7480. };
  7481. /**
  7482. * Returns the log2 of value.
  7483. */
  7484. Scalar.Log2 = function (value) {
  7485. return Math.log(value) * Math.LOG2E;
  7486. };
  7487. /**
  7488. * Loops the value, so that it is never larger than length and never smaller than 0.
  7489. *
  7490. * This is similar to the modulo operator but it works with floating point numbers.
  7491. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7492. * With t = 5 and length = 2.5, the result would be 0.0.
  7493. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7494. */
  7495. Scalar.Repeat = function (value, length) {
  7496. return value - Math.floor(value / length) * length;
  7497. };
  7498. /**
  7499. * Normalize the value between 0.0 and 1.0 using min and max values
  7500. */
  7501. Scalar.Normalize = function (value, min, max) {
  7502. return (value - min) / (max - min);
  7503. };
  7504. /**
  7505. * Denormalize the value from 0.0 and 1.0 using min and max values
  7506. */
  7507. Scalar.Denormalize = function (normalized, min, max) {
  7508. return (normalized * (max - min) + min);
  7509. };
  7510. /**
  7511. * Calculates the shortest difference between two given angles given in degrees.
  7512. */
  7513. Scalar.DeltaAngle = function (current, target) {
  7514. var num = Scalar.Repeat(target - current, 360.0);
  7515. if (num > 180.0) {
  7516. num -= 360.0;
  7517. }
  7518. return num;
  7519. };
  7520. /**
  7521. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7522. *
  7523. * The returned value will move back and forth between 0 and length
  7524. */
  7525. Scalar.PingPong = function (tx, length) {
  7526. var t = Scalar.Repeat(tx, length * 2.0);
  7527. return length - Math.abs(t - length);
  7528. };
  7529. /**
  7530. * Interpolates between min and max with smoothing at the limits.
  7531. *
  7532. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7533. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7534. */
  7535. Scalar.SmoothStep = function (from, to, tx) {
  7536. var t = Scalar.Clamp(tx);
  7537. t = -2.0 * t * t * t + 3.0 * t * t;
  7538. return to * t + from * (1.0 - t);
  7539. };
  7540. /**
  7541. * Moves a value current towards target.
  7542. *
  7543. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7544. * Negative values of maxDelta pushes the value away from target.
  7545. */
  7546. Scalar.MoveTowards = function (current, target, maxDelta) {
  7547. var result = 0;
  7548. if (Math.abs(target - current) <= maxDelta) {
  7549. result = target;
  7550. }
  7551. else {
  7552. result = current + Scalar.Sign(target - current) * maxDelta;
  7553. }
  7554. return result;
  7555. };
  7556. /**
  7557. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7558. *
  7559. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7560. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7561. */
  7562. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7563. var num = Scalar.DeltaAngle(current, target);
  7564. var result = 0;
  7565. if (-maxDelta < num && num < maxDelta) {
  7566. result = target;
  7567. }
  7568. else {
  7569. target = current + num;
  7570. result = Scalar.MoveTowards(current, target, maxDelta);
  7571. }
  7572. return result;
  7573. };
  7574. /**
  7575. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7576. */
  7577. Scalar.Lerp = function (start, end, amount) {
  7578. return start + ((end - start) * amount);
  7579. };
  7580. /**
  7581. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7582. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7583. */
  7584. Scalar.LerpAngle = function (start, end, amount) {
  7585. var num = Scalar.Repeat(end - start, 360.0);
  7586. if (num > 180.0) {
  7587. num -= 360.0;
  7588. }
  7589. return start + num * Scalar.Clamp(amount);
  7590. };
  7591. /**
  7592. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7593. */
  7594. Scalar.InverseLerp = function (a, b, value) {
  7595. var result = 0;
  7596. if (a != b) {
  7597. result = Scalar.Clamp((value - a) / (b - a));
  7598. }
  7599. else {
  7600. result = 0.0;
  7601. }
  7602. return result;
  7603. };
  7604. /**
  7605. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7606. */
  7607. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7608. var squared = amount * amount;
  7609. var cubed = amount * squared;
  7610. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7611. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7612. var part3 = (cubed - (2.0 * squared)) + amount;
  7613. var part4 = cubed - squared;
  7614. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7615. };
  7616. /**
  7617. * Returns a random float number between and min and max values
  7618. */
  7619. Scalar.RandomRange = function (min, max) {
  7620. if (min === max)
  7621. return min;
  7622. return ((Math.random() * (max - min)) + min);
  7623. };
  7624. /**
  7625. * This function returns percentage of a number in a given range.
  7626. *
  7627. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7628. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7629. */
  7630. Scalar.RangeToPercent = function (number, min, max) {
  7631. return ((number - min) / (max - min));
  7632. };
  7633. /**
  7634. * This function returns number that corresponds to the percentage in a given range.
  7635. *
  7636. * PercentToRange(0.34,0,100) will return 34.
  7637. */
  7638. Scalar.PercentToRange = function (percent, min, max) {
  7639. return ((max - min) * percent + min);
  7640. };
  7641. /**
  7642. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7643. * @param angle The angle to normalize in radian.
  7644. * @return The converted angle.
  7645. */
  7646. Scalar.NormalizeRadians = function (angle) {
  7647. // More precise but slower version kept for reference.
  7648. // angle = angle % Tools.TwoPi;
  7649. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7650. //if (angle > Math.PI) {
  7651. // angle -= Tools.TwoPi;
  7652. //}
  7653. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7654. return angle;
  7655. };
  7656. /**
  7657. * Two pi constants convenient for computation.
  7658. */
  7659. Scalar.TwoPi = Math.PI * 2;
  7660. return Scalar;
  7661. }());
  7662. BABYLON.Scalar = Scalar;
  7663. })(BABYLON || (BABYLON = {}));
  7664. //# sourceMappingURL=babylon.math.scalar.js.map
  7665. //# sourceMappingURL=babylon.mixins.js.map
  7666. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7667. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7668. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7669. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7670. //# sourceMappingURL=babylon.webgl2.js.map
  7671. var BABYLON;
  7672. (function (BABYLON) {
  7673. var __decoratorInitialStore = {};
  7674. var __mergedStore = {};
  7675. var _copySource = function (creationFunction, source, instanciate) {
  7676. var destination = creationFunction();
  7677. // Tags
  7678. if (BABYLON.Tags) {
  7679. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7680. }
  7681. var classStore = getMergedStore(destination);
  7682. // Properties
  7683. for (var property in classStore) {
  7684. var propertyDescriptor = classStore[property];
  7685. var sourceProperty = source[property];
  7686. var propertyType = propertyDescriptor.type;
  7687. if (sourceProperty !== undefined && sourceProperty !== null) {
  7688. switch (propertyType) {
  7689. case 0: // Value
  7690. case 6: // Mesh reference
  7691. case 11: // Camera reference
  7692. destination[property] = sourceProperty;
  7693. break;
  7694. case 1: // Texture
  7695. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7696. break;
  7697. case 2: // Color3
  7698. case 3: // FresnelParameters
  7699. case 4: // Vector2
  7700. case 5: // Vector3
  7701. case 7: // Color Curves
  7702. case 10: // Quaternion
  7703. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7704. break;
  7705. }
  7706. }
  7707. }
  7708. return destination;
  7709. };
  7710. function getDirectStore(target) {
  7711. var classKey = target.getClassName();
  7712. if (!__decoratorInitialStore[classKey]) {
  7713. __decoratorInitialStore[classKey] = {};
  7714. }
  7715. return __decoratorInitialStore[classKey];
  7716. }
  7717. /**
  7718. * Return the list of properties flagged as serializable
  7719. * @param target: host object
  7720. */
  7721. function getMergedStore(target) {
  7722. var classKey = target.getClassName();
  7723. if (__mergedStore[classKey]) {
  7724. return __mergedStore[classKey];
  7725. }
  7726. __mergedStore[classKey] = {};
  7727. var store = __mergedStore[classKey];
  7728. var currentTarget = target;
  7729. var currentKey = classKey;
  7730. while (currentKey) {
  7731. var initialStore = __decoratorInitialStore[currentKey];
  7732. for (var property in initialStore) {
  7733. store[property] = initialStore[property];
  7734. }
  7735. var parent_1 = void 0;
  7736. var done = false;
  7737. do {
  7738. parent_1 = Object.getPrototypeOf(currentTarget);
  7739. if (!parent_1.getClassName) {
  7740. done = true;
  7741. break;
  7742. }
  7743. if (parent_1.getClassName() !== currentKey) {
  7744. break;
  7745. }
  7746. currentTarget = parent_1;
  7747. } while (parent_1);
  7748. if (done) {
  7749. break;
  7750. }
  7751. currentKey = parent_1.getClassName();
  7752. currentTarget = parent_1;
  7753. }
  7754. return store;
  7755. }
  7756. function generateSerializableMember(type, sourceName) {
  7757. return function (target, propertyKey) {
  7758. var classStore = getDirectStore(target);
  7759. if (!classStore[propertyKey]) {
  7760. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7761. }
  7762. };
  7763. }
  7764. function generateExpandMember(setCallback, targetKey) {
  7765. if (targetKey === void 0) { targetKey = null; }
  7766. return function (target, propertyKey) {
  7767. var key = targetKey || ("_" + propertyKey);
  7768. Object.defineProperty(target, propertyKey, {
  7769. get: function () {
  7770. return this[key];
  7771. },
  7772. set: function (value) {
  7773. if (this[key] === value) {
  7774. return;
  7775. }
  7776. this[key] = value;
  7777. target[setCallback].apply(this);
  7778. },
  7779. enumerable: true,
  7780. configurable: true
  7781. });
  7782. };
  7783. }
  7784. function expandToProperty(callback, targetKey) {
  7785. if (targetKey === void 0) { targetKey = null; }
  7786. return generateExpandMember(callback, targetKey);
  7787. }
  7788. BABYLON.expandToProperty = expandToProperty;
  7789. function serialize(sourceName) {
  7790. return generateSerializableMember(0, sourceName); // value member
  7791. }
  7792. BABYLON.serialize = serialize;
  7793. function serializeAsTexture(sourceName) {
  7794. return generateSerializableMember(1, sourceName); // texture member
  7795. }
  7796. BABYLON.serializeAsTexture = serializeAsTexture;
  7797. function serializeAsColor3(sourceName) {
  7798. return generateSerializableMember(2, sourceName); // color3 member
  7799. }
  7800. BABYLON.serializeAsColor3 = serializeAsColor3;
  7801. function serializeAsFresnelParameters(sourceName) {
  7802. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7803. }
  7804. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7805. function serializeAsVector2(sourceName) {
  7806. return generateSerializableMember(4, sourceName); // vector2 member
  7807. }
  7808. BABYLON.serializeAsVector2 = serializeAsVector2;
  7809. function serializeAsVector3(sourceName) {
  7810. return generateSerializableMember(5, sourceName); // vector3 member
  7811. }
  7812. BABYLON.serializeAsVector3 = serializeAsVector3;
  7813. function serializeAsMeshReference(sourceName) {
  7814. return generateSerializableMember(6, sourceName); // mesh reference member
  7815. }
  7816. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7817. function serializeAsColorCurves(sourceName) {
  7818. return generateSerializableMember(7, sourceName); // color curves
  7819. }
  7820. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7821. function serializeAsColor4(sourceName) {
  7822. return generateSerializableMember(8, sourceName); // color 4
  7823. }
  7824. BABYLON.serializeAsColor4 = serializeAsColor4;
  7825. function serializeAsImageProcessingConfiguration(sourceName) {
  7826. return generateSerializableMember(9, sourceName); // image processing
  7827. }
  7828. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7829. function serializeAsQuaternion(sourceName) {
  7830. return generateSerializableMember(10, sourceName); // quaternion member
  7831. }
  7832. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7833. /**
  7834. * Decorator used to define property that can be serialized as reference to a camera
  7835. * @param sourceName defines the name of the property to decorate
  7836. */
  7837. function serializeAsCameraReference(sourceName) {
  7838. return generateSerializableMember(11, sourceName); // camera reference member
  7839. }
  7840. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7841. var SerializationHelper = /** @class */ (function () {
  7842. function SerializationHelper() {
  7843. }
  7844. SerializationHelper.Serialize = function (entity, serializationObject) {
  7845. if (!serializationObject) {
  7846. serializationObject = {};
  7847. }
  7848. // Tags
  7849. if (BABYLON.Tags) {
  7850. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7851. }
  7852. var serializedProperties = getMergedStore(entity);
  7853. // Properties
  7854. for (var property in serializedProperties) {
  7855. var propertyDescriptor = serializedProperties[property];
  7856. var targetPropertyName = propertyDescriptor.sourceName || property;
  7857. var propertyType = propertyDescriptor.type;
  7858. var sourceProperty = entity[property];
  7859. if (sourceProperty !== undefined && sourceProperty !== null) {
  7860. switch (propertyType) {
  7861. case 0: // Value
  7862. serializationObject[targetPropertyName] = sourceProperty;
  7863. break;
  7864. case 1: // Texture
  7865. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7866. break;
  7867. case 2: // Color3
  7868. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7869. break;
  7870. case 3: // FresnelParameters
  7871. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7872. break;
  7873. case 4: // Vector2
  7874. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7875. break;
  7876. case 5: // Vector3
  7877. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7878. break;
  7879. case 6: // Mesh reference
  7880. serializationObject[targetPropertyName] = sourceProperty.id;
  7881. break;
  7882. case 7: // Color Curves
  7883. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7884. break;
  7885. case 8: // Color 4
  7886. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7887. break;
  7888. case 9: // Image Processing
  7889. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7890. break;
  7891. case 10: // Quaternion
  7892. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7893. break;
  7894. case 11: // Camera reference
  7895. serializationObject[targetPropertyName] = sourceProperty.id;
  7896. break;
  7897. }
  7898. }
  7899. }
  7900. return serializationObject;
  7901. };
  7902. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7903. if (rootUrl === void 0) { rootUrl = null; }
  7904. var destination = creationFunction();
  7905. if (!rootUrl) {
  7906. rootUrl = "";
  7907. }
  7908. // Tags
  7909. if (BABYLON.Tags) {
  7910. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7911. }
  7912. var classStore = getMergedStore(destination);
  7913. // Properties
  7914. for (var property in classStore) {
  7915. var propertyDescriptor = classStore[property];
  7916. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7917. var propertyType = propertyDescriptor.type;
  7918. if (sourceProperty !== undefined && sourceProperty !== null) {
  7919. var dest = destination;
  7920. switch (propertyType) {
  7921. case 0: // Value
  7922. dest[property] = sourceProperty;
  7923. break;
  7924. case 1: // Texture
  7925. if (scene) {
  7926. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7927. }
  7928. break;
  7929. case 2: // Color3
  7930. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7931. break;
  7932. case 3: // FresnelParameters
  7933. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7934. break;
  7935. case 4: // Vector2
  7936. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7937. break;
  7938. case 5: // Vector3
  7939. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7940. break;
  7941. case 6: // Mesh reference
  7942. if (scene) {
  7943. dest[property] = scene.getLastMeshByID(sourceProperty);
  7944. }
  7945. break;
  7946. case 7: // Color Curves
  7947. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7948. break;
  7949. case 8: // Color 4
  7950. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7951. break;
  7952. case 9: // Image Processing
  7953. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7954. break;
  7955. case 10: // Quaternion
  7956. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7957. break;
  7958. case 11: // Camera reference
  7959. if (scene) {
  7960. dest[property] = scene.getCameraByID(sourceProperty);
  7961. }
  7962. break;
  7963. }
  7964. }
  7965. }
  7966. return destination;
  7967. };
  7968. SerializationHelper.Clone = function (creationFunction, source) {
  7969. return _copySource(creationFunction, source, false);
  7970. };
  7971. SerializationHelper.Instanciate = function (creationFunction, source) {
  7972. return _copySource(creationFunction, source, true);
  7973. };
  7974. return SerializationHelper;
  7975. }());
  7976. BABYLON.SerializationHelper = SerializationHelper;
  7977. })(BABYLON || (BABYLON = {}));
  7978. //# sourceMappingURL=babylon.decorators.js.map
  7979. var BABYLON;
  7980. (function (BABYLON) {
  7981. /**
  7982. * Wrapper class for promise with external resolve and reject.
  7983. */
  7984. var Deferred = /** @class */ (function () {
  7985. /**
  7986. * Constructor for this deferred object.
  7987. */
  7988. function Deferred() {
  7989. var _this = this;
  7990. this.promise = new Promise(function (resolve, reject) {
  7991. _this._resolve = resolve;
  7992. _this._reject = reject;
  7993. });
  7994. }
  7995. Object.defineProperty(Deferred.prototype, "resolve", {
  7996. /**
  7997. * The resolve method of the promise associated with this deferred object.
  7998. */
  7999. get: function () {
  8000. return this._resolve;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Deferred.prototype, "reject", {
  8006. /**
  8007. * The reject method of the promise associated with this deferred object.
  8008. */
  8009. get: function () {
  8010. return this._reject;
  8011. },
  8012. enumerable: true,
  8013. configurable: true
  8014. });
  8015. return Deferred;
  8016. }());
  8017. BABYLON.Deferred = Deferred;
  8018. })(BABYLON || (BABYLON = {}));
  8019. //# sourceMappingURL=babylon.deferred.js.map
  8020. var BABYLON;
  8021. (function (BABYLON) {
  8022. /**
  8023. * A class serves as a medium between the observable and its observers
  8024. */
  8025. var EventState = /** @class */ (function () {
  8026. /**
  8027. * Create a new EventState
  8028. * @param mask defines the mask associated with this state
  8029. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8030. * @param target defines the original target of the state
  8031. * @param currentTarget defines the current target of the state
  8032. */
  8033. function EventState(mask, skipNextObservers, target, currentTarget) {
  8034. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8035. this.initalize(mask, skipNextObservers, target, currentTarget);
  8036. }
  8037. /**
  8038. * Initialize the current event state
  8039. * @param mask defines the mask associated with this state
  8040. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8041. * @param target defines the original target of the state
  8042. * @param currentTarget defines the current target of the state
  8043. * @returns the current event state
  8044. */
  8045. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8046. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8047. this.mask = mask;
  8048. this.skipNextObservers = skipNextObservers;
  8049. this.target = target;
  8050. this.currentTarget = currentTarget;
  8051. return this;
  8052. };
  8053. return EventState;
  8054. }());
  8055. BABYLON.EventState = EventState;
  8056. /**
  8057. * Represent an Observer registered to a given Observable object.
  8058. */
  8059. var Observer = /** @class */ (function () {
  8060. /**
  8061. * Creates a new observer
  8062. * @param callback defines the callback to call when the observer is notified
  8063. * @param mask defines the mask of the observer (used to filter notifications)
  8064. * @param scope defines the current scope used to restore the JS context
  8065. */
  8066. function Observer(
  8067. /**
  8068. * Defines the callback to call when the observer is notified
  8069. */
  8070. callback,
  8071. /**
  8072. * Defines the mask of the observer (used to filter notifications)
  8073. */
  8074. mask,
  8075. /**
  8076. * Defines the current scope used to restore the JS context
  8077. */
  8078. scope) {
  8079. if (scope === void 0) { scope = null; }
  8080. this.callback = callback;
  8081. this.mask = mask;
  8082. this.scope = scope;
  8083. /** @hidden */
  8084. this._willBeUnregistered = false;
  8085. /**
  8086. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8087. */
  8088. this.unregisterOnNextCall = false;
  8089. }
  8090. return Observer;
  8091. }());
  8092. BABYLON.Observer = Observer;
  8093. /**
  8094. * Represent a list of observers registered to multiple Observables object.
  8095. */
  8096. var MultiObserver = /** @class */ (function () {
  8097. function MultiObserver() {
  8098. }
  8099. /**
  8100. * Release associated resources
  8101. */
  8102. MultiObserver.prototype.dispose = function () {
  8103. if (this._observers && this._observables) {
  8104. for (var index = 0; index < this._observers.length; index++) {
  8105. this._observables[index].remove(this._observers[index]);
  8106. }
  8107. }
  8108. this._observers = null;
  8109. this._observables = null;
  8110. };
  8111. /**
  8112. * Raise a callback when one of the observable will notify
  8113. * @param observables defines a list of observables to watch
  8114. * @param callback defines the callback to call on notification
  8115. * @param mask defines the mask used to filter notifications
  8116. * @param scope defines the current scope used to restore the JS context
  8117. * @returns the new MultiObserver
  8118. */
  8119. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8120. if (mask === void 0) { mask = -1; }
  8121. if (scope === void 0) { scope = null; }
  8122. var result = new MultiObserver();
  8123. result._observers = new Array();
  8124. result._observables = observables;
  8125. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8126. var observable = observables_1[_i];
  8127. var observer = observable.add(callback, mask, false, scope);
  8128. if (observer) {
  8129. result._observers.push(observer);
  8130. }
  8131. }
  8132. return result;
  8133. };
  8134. return MultiObserver;
  8135. }());
  8136. BABYLON.MultiObserver = MultiObserver;
  8137. /**
  8138. * The Observable class is a simple implementation of the Observable pattern.
  8139. *
  8140. * 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.
  8141. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8142. * 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).
  8143. * 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.
  8144. */
  8145. var Observable = /** @class */ (function () {
  8146. /**
  8147. * Creates a new observable
  8148. * @param onObserverAdded defines a callback to call when a new observer is added
  8149. */
  8150. function Observable(onObserverAdded) {
  8151. this._observers = new Array();
  8152. this._eventState = new EventState(0);
  8153. if (onObserverAdded) {
  8154. this._onObserverAdded = onObserverAdded;
  8155. }
  8156. }
  8157. /**
  8158. * Create a new Observer with the specified callback
  8159. * @param callback the callback that will be executed for that Observer
  8160. * @param mask the mask used to filter observers
  8161. * @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.
  8162. * @param scope optional scope for the callback to be called from
  8163. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8164. * @returns the new observer created for the callback
  8165. */
  8166. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8167. if (mask === void 0) { mask = -1; }
  8168. if (insertFirst === void 0) { insertFirst = false; }
  8169. if (scope === void 0) { scope = null; }
  8170. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8171. if (!callback) {
  8172. return null;
  8173. }
  8174. var observer = new Observer(callback, mask, scope);
  8175. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8176. if (insertFirst) {
  8177. this._observers.unshift(observer);
  8178. }
  8179. else {
  8180. this._observers.push(observer);
  8181. }
  8182. if (this._onObserverAdded) {
  8183. this._onObserverAdded(observer);
  8184. }
  8185. return observer;
  8186. };
  8187. /**
  8188. * Create a new Observer with the specified callback and unregisters after the next notification
  8189. * @param callback the callback that will be executed for that Observer
  8190. * @returns the new observer created for the callback
  8191. */
  8192. Observable.prototype.addOnce = function (callback) {
  8193. return this.add(callback, undefined, undefined, undefined, true);
  8194. };
  8195. /**
  8196. * Remove an Observer from the Observable object
  8197. * @param observer the instance of the Observer to remove
  8198. * @returns false if it doesn't belong to this Observable
  8199. */
  8200. Observable.prototype.remove = function (observer) {
  8201. if (!observer) {
  8202. return false;
  8203. }
  8204. var index = this._observers.indexOf(observer);
  8205. if (index !== -1) {
  8206. this._observers.splice(index, 1);
  8207. return true;
  8208. }
  8209. return false;
  8210. };
  8211. /**
  8212. * Remove a callback from the Observable object
  8213. * @param callback the callback to remove
  8214. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8215. * @returns false if it doesn't belong to this Observable
  8216. */
  8217. Observable.prototype.removeCallback = function (callback, scope) {
  8218. for (var index = 0; index < this._observers.length; index++) {
  8219. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8220. this._observers.splice(index, 1);
  8221. return true;
  8222. }
  8223. }
  8224. return false;
  8225. };
  8226. Observable.prototype._deferUnregister = function (observer) {
  8227. var _this = this;
  8228. observer.unregisterOnNextCall = false;
  8229. observer._willBeUnregistered = true;
  8230. BABYLON.Tools.SetImmediate(function () {
  8231. _this.remove(observer);
  8232. });
  8233. };
  8234. /**
  8235. * Notify all Observers by calling their respective callback with the given data
  8236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8237. * @param eventData defines the data to send to all observers
  8238. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8239. * @param target defines the original target of the state
  8240. * @param currentTarget defines the current target of the state
  8241. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8242. */
  8243. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8244. if (mask === void 0) { mask = -1; }
  8245. if (!this._observers.length) {
  8246. return true;
  8247. }
  8248. var state = this._eventState;
  8249. state.mask = mask;
  8250. state.target = target;
  8251. state.currentTarget = currentTarget;
  8252. state.skipNextObservers = false;
  8253. state.lastReturnValue = eventData;
  8254. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8255. var obs = _a[_i];
  8256. if (obs._willBeUnregistered) {
  8257. continue;
  8258. }
  8259. if (obs.mask & mask) {
  8260. if (obs.scope) {
  8261. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8262. }
  8263. else {
  8264. state.lastReturnValue = obs.callback(eventData, state);
  8265. }
  8266. if (obs.unregisterOnNextCall) {
  8267. this._deferUnregister(obs);
  8268. }
  8269. }
  8270. if (state.skipNextObservers) {
  8271. return false;
  8272. }
  8273. }
  8274. return true;
  8275. };
  8276. /**
  8277. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8278. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8279. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8280. * and it is crucial that all callbacks will be executed.
  8281. * The order of the callbacks is kept, callbacks are not executed parallel.
  8282. *
  8283. * @param eventData The data to be sent to each callback
  8284. * @param mask is used to filter observers defaults to -1
  8285. * @param target defines the callback target (see EventState)
  8286. * @param currentTarget defines he current object in the bubbling phase
  8287. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8288. */
  8289. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8290. var _this = this;
  8291. if (mask === void 0) { mask = -1; }
  8292. // create an empty promise
  8293. var p = Promise.resolve(eventData);
  8294. // no observers? return this promise.
  8295. if (!this._observers.length) {
  8296. return p;
  8297. }
  8298. var state = this._eventState;
  8299. state.mask = mask;
  8300. state.target = target;
  8301. state.currentTarget = currentTarget;
  8302. state.skipNextObservers = false;
  8303. // execute one callback after another (not using Promise.all, the order is important)
  8304. this._observers.forEach(function (obs) {
  8305. if (state.skipNextObservers) {
  8306. return;
  8307. }
  8308. if (obs._willBeUnregistered) {
  8309. return;
  8310. }
  8311. if (obs.mask & mask) {
  8312. if (obs.scope) {
  8313. p = p.then(function (lastReturnedValue) {
  8314. state.lastReturnValue = lastReturnedValue;
  8315. return obs.callback.apply(obs.scope, [eventData, state]);
  8316. });
  8317. }
  8318. else {
  8319. p = p.then(function (lastReturnedValue) {
  8320. state.lastReturnValue = lastReturnedValue;
  8321. return obs.callback(eventData, state);
  8322. });
  8323. }
  8324. if (obs.unregisterOnNextCall) {
  8325. _this._deferUnregister(obs);
  8326. }
  8327. }
  8328. });
  8329. // return the eventData
  8330. return p.then(function () { return eventData; });
  8331. };
  8332. /**
  8333. * Notify a specific observer
  8334. * @param observer defines the observer to notify
  8335. * @param eventData defines the data to be sent to each callback
  8336. * @param mask is used to filter observers defaults to -1
  8337. */
  8338. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8339. if (mask === void 0) { mask = -1; }
  8340. var state = this._eventState;
  8341. state.mask = mask;
  8342. state.skipNextObservers = false;
  8343. observer.callback(eventData, state);
  8344. };
  8345. /**
  8346. * Gets a boolean indicating if the observable has at least one observer
  8347. * @returns true is the Observable has at least one Observer registered
  8348. */
  8349. Observable.prototype.hasObservers = function () {
  8350. return this._observers.length > 0;
  8351. };
  8352. /**
  8353. * Clear the list of observers
  8354. */
  8355. Observable.prototype.clear = function () {
  8356. this._observers = new Array();
  8357. this._onObserverAdded = null;
  8358. };
  8359. /**
  8360. * Clone the current observable
  8361. * @returns a new observable
  8362. */
  8363. Observable.prototype.clone = function () {
  8364. var result = new Observable();
  8365. result._observers = this._observers.slice(0);
  8366. return result;
  8367. };
  8368. /**
  8369. * Does this observable handles observer registered with a given mask
  8370. * @param mask defines the mask to be tested
  8371. * @return whether or not one observer registered with the given mask is handeled
  8372. **/
  8373. Observable.prototype.hasSpecificMask = function (mask) {
  8374. if (mask === void 0) { mask = -1; }
  8375. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8376. var obs = _a[_i];
  8377. if (obs.mask & mask || obs.mask === mask) {
  8378. return true;
  8379. }
  8380. }
  8381. return false;
  8382. };
  8383. return Observable;
  8384. }());
  8385. BABYLON.Observable = Observable;
  8386. })(BABYLON || (BABYLON = {}));
  8387. //# sourceMappingURL=babylon.observable.js.map
  8388. var BABYLON;
  8389. (function (BABYLON) {
  8390. var SmartArray = /** @class */ (function () {
  8391. function SmartArray(capacity) {
  8392. this.length = 0;
  8393. this.data = new Array(capacity);
  8394. this._id = SmartArray._GlobalId++;
  8395. }
  8396. SmartArray.prototype.push = function (value) {
  8397. this.data[this.length++] = value;
  8398. if (this.length > this.data.length) {
  8399. this.data.length *= 2;
  8400. }
  8401. };
  8402. SmartArray.prototype.forEach = function (func) {
  8403. for (var index = 0; index < this.length; index++) {
  8404. func(this.data[index]);
  8405. }
  8406. };
  8407. SmartArray.prototype.sort = function (compareFn) {
  8408. this.data.sort(compareFn);
  8409. };
  8410. SmartArray.prototype.reset = function () {
  8411. this.length = 0;
  8412. };
  8413. SmartArray.prototype.dispose = function () {
  8414. this.reset();
  8415. if (this.data) {
  8416. this.data.length = 0;
  8417. this.data = [];
  8418. }
  8419. };
  8420. SmartArray.prototype.concat = function (array) {
  8421. if (array.length === 0) {
  8422. return;
  8423. }
  8424. if (this.length + array.length > this.data.length) {
  8425. this.data.length = (this.length + array.length) * 2;
  8426. }
  8427. for (var index = 0; index < array.length; index++) {
  8428. this.data[this.length++] = (array.data || array)[index];
  8429. }
  8430. };
  8431. SmartArray.prototype.indexOf = function (value) {
  8432. var position = this.data.indexOf(value);
  8433. if (position >= this.length) {
  8434. return -1;
  8435. }
  8436. return position;
  8437. };
  8438. SmartArray.prototype.contains = function (value) {
  8439. return this.data.indexOf(value) !== -1;
  8440. };
  8441. // Statics
  8442. SmartArray._GlobalId = 0;
  8443. return SmartArray;
  8444. }());
  8445. BABYLON.SmartArray = SmartArray;
  8446. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8447. __extends(SmartArrayNoDuplicate, _super);
  8448. function SmartArrayNoDuplicate() {
  8449. var _this = _super !== null && _super.apply(this, arguments) || this;
  8450. _this._duplicateId = 0;
  8451. return _this;
  8452. }
  8453. SmartArrayNoDuplicate.prototype.push = function (value) {
  8454. _super.prototype.push.call(this, value);
  8455. if (!value.__smartArrayFlags) {
  8456. value.__smartArrayFlags = {};
  8457. }
  8458. value.__smartArrayFlags[this._id] = this._duplicateId;
  8459. };
  8460. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8461. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8462. return false;
  8463. }
  8464. this.push(value);
  8465. return true;
  8466. };
  8467. SmartArrayNoDuplicate.prototype.reset = function () {
  8468. _super.prototype.reset.call(this);
  8469. this._duplicateId++;
  8470. };
  8471. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8472. if (array.length === 0) {
  8473. return;
  8474. }
  8475. if (this.length + array.length > this.data.length) {
  8476. this.data.length = (this.length + array.length) * 2;
  8477. }
  8478. for (var index = 0; index < array.length; index++) {
  8479. var item = (array.data || array)[index];
  8480. this.pushNoDuplicate(item);
  8481. }
  8482. };
  8483. return SmartArrayNoDuplicate;
  8484. }(SmartArray));
  8485. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8486. })(BABYLON || (BABYLON = {}));
  8487. //# sourceMappingURL=babylon.smartArray.js.map
  8488. var BABYLON;
  8489. (function (BABYLON) {
  8490. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8491. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8492. var LoadFileError = /** @class */ (function (_super) {
  8493. __extends(LoadFileError, _super);
  8494. function LoadFileError(message, request) {
  8495. var _this = _super.call(this, message) || this;
  8496. _this.request = request;
  8497. _this.name = "LoadFileError";
  8498. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8499. return _this;
  8500. }
  8501. // Polyfill for Object.setPrototypeOf if necessary.
  8502. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8503. return LoadFileError;
  8504. }(Error));
  8505. BABYLON.LoadFileError = LoadFileError;
  8506. var RetryStrategy = /** @class */ (function () {
  8507. function RetryStrategy() {
  8508. }
  8509. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8510. if (maxRetries === void 0) { maxRetries = 3; }
  8511. if (baseInterval === void 0) { baseInterval = 500; }
  8512. return function (url, request, retryIndex) {
  8513. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8514. return -1;
  8515. }
  8516. return Math.pow(2, retryIndex) * baseInterval;
  8517. };
  8518. };
  8519. return RetryStrategy;
  8520. }());
  8521. BABYLON.RetryStrategy = RetryStrategy;
  8522. // Screenshots
  8523. var screenshotCanvas;
  8524. var cloneValue = function (source, destinationObject) {
  8525. if (!source)
  8526. return null;
  8527. if (source instanceof BABYLON.Mesh) {
  8528. return null;
  8529. }
  8530. if (source instanceof BABYLON.SubMesh) {
  8531. return source.clone(destinationObject);
  8532. }
  8533. else if (source.clone) {
  8534. return source.clone();
  8535. }
  8536. return null;
  8537. };
  8538. var Tools = /** @class */ (function () {
  8539. function Tools() {
  8540. }
  8541. /**
  8542. * Interpolates between a and b via alpha
  8543. * @param a The lower value (returned when alpha = 0)
  8544. * @param b The upper value (returned when alpha = 1)
  8545. * @param alpha The interpolation-factor
  8546. * @return The mixed value
  8547. */
  8548. Tools.Mix = function (a, b, alpha) {
  8549. return a * (1 - alpha) + b * alpha;
  8550. };
  8551. Tools.Instantiate = function (className) {
  8552. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8553. return Tools.RegisteredExternalClasses[className];
  8554. }
  8555. var arr = className.split(".");
  8556. var fn = (window || this);
  8557. for (var i = 0, len = arr.length; i < len; i++) {
  8558. fn = fn[arr[i]];
  8559. }
  8560. if (typeof fn !== "function") {
  8561. return null;
  8562. }
  8563. return fn;
  8564. };
  8565. /**
  8566. * Provides a slice function that will work even on IE
  8567. * @param data defines the array to slice
  8568. * @param start defines the start of the data (optional)
  8569. * @param end defines the end of the data (optional)
  8570. * @returns the new sliced array
  8571. */
  8572. Tools.Slice = function (data, start, end) {
  8573. if (data.slice) {
  8574. return data.slice(start, end);
  8575. }
  8576. return Array.prototype.slice.call(data, start, end);
  8577. };
  8578. Tools.SetImmediate = function (action) {
  8579. if (window.setImmediate) {
  8580. window.setImmediate(action);
  8581. }
  8582. else {
  8583. setTimeout(action, 1);
  8584. }
  8585. };
  8586. Tools.IsExponentOfTwo = function (value) {
  8587. var count = 1;
  8588. do {
  8589. count *= 2;
  8590. } while (count < value);
  8591. return count === value;
  8592. };
  8593. /**
  8594. * Returns the nearest 32-bit single precision float representation of a Number
  8595. * @param value A Number. If the parameter is of a different type, it will get converted
  8596. * to a number or to NaN if it cannot be converted
  8597. * @returns number
  8598. */
  8599. Tools.FloatRound = function (value) {
  8600. if (Math.fround) {
  8601. return Math.fround(value);
  8602. }
  8603. return (Tools._tmpFloatArray[0] = value);
  8604. };
  8605. /**
  8606. * Find the next highest power of two.
  8607. * @param x Number to start search from.
  8608. * @return Next highest power of two.
  8609. */
  8610. Tools.CeilingPOT = function (x) {
  8611. x--;
  8612. x |= x >> 1;
  8613. x |= x >> 2;
  8614. x |= x >> 4;
  8615. x |= x >> 8;
  8616. x |= x >> 16;
  8617. x++;
  8618. return x;
  8619. };
  8620. /**
  8621. * Find the next lowest power of two.
  8622. * @param x Number to start search from.
  8623. * @return Next lowest power of two.
  8624. */
  8625. Tools.FloorPOT = function (x) {
  8626. x = x | (x >> 1);
  8627. x = x | (x >> 2);
  8628. x = x | (x >> 4);
  8629. x = x | (x >> 8);
  8630. x = x | (x >> 16);
  8631. return x - (x >> 1);
  8632. };
  8633. /**
  8634. * Find the nearest power of two.
  8635. * @param x Number to start search from.
  8636. * @return Next nearest power of two.
  8637. */
  8638. Tools.NearestPOT = function (x) {
  8639. var c = Tools.CeilingPOT(x);
  8640. var f = Tools.FloorPOT(x);
  8641. return (c - x) > (x - f) ? f : c;
  8642. };
  8643. Tools.GetExponentOfTwo = function (value, max, mode) {
  8644. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8645. var pot;
  8646. switch (mode) {
  8647. case BABYLON.Engine.SCALEMODE_FLOOR:
  8648. pot = Tools.FloorPOT(value);
  8649. break;
  8650. case BABYLON.Engine.SCALEMODE_NEAREST:
  8651. pot = Tools.NearestPOT(value);
  8652. break;
  8653. case BABYLON.Engine.SCALEMODE_CEILING:
  8654. default:
  8655. pot = Tools.CeilingPOT(value);
  8656. break;
  8657. }
  8658. return Math.min(pot, max);
  8659. };
  8660. Tools.GetFilename = function (path) {
  8661. var index = path.lastIndexOf("/");
  8662. if (index < 0)
  8663. return path;
  8664. return path.substring(index + 1);
  8665. };
  8666. /**
  8667. * Extracts the "folder" part of a path (everything before the filename).
  8668. * @param uri The URI to extract the info from
  8669. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8670. * @returns The "folder" part of the path
  8671. */
  8672. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8673. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8674. var index = uri.lastIndexOf("/");
  8675. if (index < 0) {
  8676. if (returnUnchangedIfNoSlash) {
  8677. return uri;
  8678. }
  8679. return "";
  8680. }
  8681. return uri.substring(0, index + 1);
  8682. };
  8683. Tools.GetDOMTextContent = function (element) {
  8684. var result = "";
  8685. var child = element.firstChild;
  8686. while (child) {
  8687. if (child.nodeType === 3) {
  8688. result += child.textContent;
  8689. }
  8690. child = child.nextSibling;
  8691. }
  8692. return result;
  8693. };
  8694. Tools.ToDegrees = function (angle) {
  8695. return angle * 180 / Math.PI;
  8696. };
  8697. Tools.ToRadians = function (angle) {
  8698. return angle * Math.PI / 180;
  8699. };
  8700. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8701. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8702. var output = "";
  8703. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8704. var i = 0;
  8705. var bytes = new Uint8Array(buffer);
  8706. while (i < bytes.length) {
  8707. chr1 = bytes[i++];
  8708. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8709. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8710. enc1 = chr1 >> 2;
  8711. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8712. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8713. enc4 = chr3 & 63;
  8714. if (isNaN(chr2)) {
  8715. enc3 = enc4 = 64;
  8716. }
  8717. else if (isNaN(chr3)) {
  8718. enc4 = 64;
  8719. }
  8720. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8721. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8722. }
  8723. return "data:image/png;base64," + output;
  8724. };
  8725. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8726. if (bias === void 0) { bias = null; }
  8727. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8728. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8729. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8730. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8731. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8732. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8733. }
  8734. if (bias) {
  8735. minimum.x -= minimum.x * bias.x + bias.y;
  8736. minimum.y -= minimum.y * bias.x + bias.y;
  8737. minimum.z -= minimum.z * bias.x + bias.y;
  8738. maximum.x += maximum.x * bias.x + bias.y;
  8739. maximum.y += maximum.y * bias.x + bias.y;
  8740. maximum.z += maximum.z * bias.x + bias.y;
  8741. }
  8742. return {
  8743. minimum: minimum,
  8744. maximum: maximum
  8745. };
  8746. };
  8747. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8748. if (bias === void 0) { bias = null; }
  8749. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8750. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8751. if (!stride) {
  8752. stride = 3;
  8753. }
  8754. for (var index = start; index < start + count; index++) {
  8755. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8756. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8757. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8758. }
  8759. if (bias) {
  8760. minimum.x -= minimum.x * bias.x + bias.y;
  8761. minimum.y -= minimum.y * bias.x + bias.y;
  8762. minimum.z -= minimum.z * bias.x + bias.y;
  8763. maximum.x += maximum.x * bias.x + bias.y;
  8764. maximum.y += maximum.y * bias.x + bias.y;
  8765. maximum.z += maximum.z * bias.x + bias.y;
  8766. }
  8767. return {
  8768. minimum: minimum,
  8769. maximum: maximum
  8770. };
  8771. };
  8772. Tools.Vector2ArrayFeeder = function (array) {
  8773. return function (index) {
  8774. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8775. var length = isFloatArray ? array.length / 2 : array.length;
  8776. if (index >= length) {
  8777. return null;
  8778. }
  8779. if (isFloatArray) {
  8780. var fa = array;
  8781. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8782. }
  8783. var a = array;
  8784. return a[index];
  8785. };
  8786. };
  8787. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8788. if (bias === void 0) { bias = null; }
  8789. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8790. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8791. var i = 0;
  8792. var cur = feeder(i++);
  8793. while (cur) {
  8794. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8795. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8796. cur = feeder(i++);
  8797. }
  8798. if (bias) {
  8799. minimum.x -= minimum.x * bias.x + bias.y;
  8800. minimum.y -= minimum.y * bias.x + bias.y;
  8801. maximum.x += maximum.x * bias.x + bias.y;
  8802. maximum.y += maximum.y * bias.x + bias.y;
  8803. }
  8804. return {
  8805. minimum: minimum,
  8806. maximum: maximum
  8807. };
  8808. };
  8809. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8810. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8811. return null;
  8812. return Array.isArray(obj) ? obj : [obj];
  8813. };
  8814. // Misc.
  8815. Tools.GetPointerPrefix = function () {
  8816. var eventPrefix = "pointer";
  8817. // Check if pointer events are supported
  8818. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8819. eventPrefix = "mouse";
  8820. }
  8821. return eventPrefix;
  8822. };
  8823. /**
  8824. * @param func - the function to be called
  8825. * @param requester - the object that will request the next frame. Falls back to window.
  8826. */
  8827. Tools.QueueNewFrame = function (func, requester) {
  8828. if (!Tools.IsWindowObjectExist()) {
  8829. return setTimeout(func, 16);
  8830. }
  8831. if (!requester) {
  8832. requester = window;
  8833. }
  8834. if (requester.requestAnimationFrame) {
  8835. return requester.requestAnimationFrame(func);
  8836. }
  8837. else if (requester.msRequestAnimationFrame) {
  8838. return requester.msRequestAnimationFrame(func);
  8839. }
  8840. else if (requester.webkitRequestAnimationFrame) {
  8841. return requester.webkitRequestAnimationFrame(func);
  8842. }
  8843. else if (requester.mozRequestAnimationFrame) {
  8844. return requester.mozRequestAnimationFrame(func);
  8845. }
  8846. else if (requester.oRequestAnimationFrame) {
  8847. return requester.oRequestAnimationFrame(func);
  8848. }
  8849. else {
  8850. return window.setTimeout(func, 16);
  8851. }
  8852. };
  8853. Tools.RequestFullscreen = function (element) {
  8854. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8855. if (!requestFunction)
  8856. return;
  8857. requestFunction.call(element);
  8858. };
  8859. Tools.ExitFullscreen = function () {
  8860. if (document.exitFullscreen) {
  8861. document.exitFullscreen();
  8862. }
  8863. else if (document.mozCancelFullScreen) {
  8864. document.mozCancelFullScreen();
  8865. }
  8866. else if (document.webkitCancelFullScreen) {
  8867. document.webkitCancelFullScreen();
  8868. }
  8869. else if (document.msCancelFullScreen) {
  8870. document.msCancelFullScreen();
  8871. }
  8872. };
  8873. Tools.SetCorsBehavior = function (url, element) {
  8874. if (url && url.indexOf("data:") === 0) {
  8875. return;
  8876. }
  8877. if (Tools.CorsBehavior) {
  8878. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8879. element.crossOrigin = Tools.CorsBehavior;
  8880. }
  8881. else {
  8882. var result = Tools.CorsBehavior(url);
  8883. if (result) {
  8884. element.crossOrigin = result;
  8885. }
  8886. }
  8887. }
  8888. };
  8889. // External files
  8890. Tools.CleanUrl = function (url) {
  8891. url = url.replace(/#/mg, "%23");
  8892. return url;
  8893. };
  8894. /**
  8895. * Loads an image as an HTMLImageElement.
  8896. * @param input url string, ArrayBuffer, or Blob to load
  8897. * @param onLoad callback called when the image successfully loads
  8898. * @param onError callback called when the image fails to load
  8899. * @param database database for caching
  8900. * @returns the HTMLImageElement of the loaded image
  8901. */
  8902. Tools.LoadImage = function (input, onLoad, onError, database) {
  8903. var url;
  8904. var usingObjectURL = false;
  8905. if (input instanceof ArrayBuffer) {
  8906. url = URL.createObjectURL(new Blob([input]));
  8907. usingObjectURL = true;
  8908. }
  8909. else if (input instanceof Blob) {
  8910. url = URL.createObjectURL(input);
  8911. usingObjectURL = true;
  8912. }
  8913. else {
  8914. url = Tools.CleanUrl(input);
  8915. url = Tools.PreprocessUrl(input);
  8916. }
  8917. var img = new Image();
  8918. Tools.SetCorsBehavior(url, img);
  8919. var loadHandler = function () {
  8920. if (usingObjectURL && img.src) {
  8921. URL.revokeObjectURL(img.src);
  8922. }
  8923. img.removeEventListener("load", loadHandler);
  8924. img.removeEventListener("error", errorHandler);
  8925. onLoad(img);
  8926. };
  8927. var errorHandler = function (err) {
  8928. if (usingObjectURL && img.src) {
  8929. URL.revokeObjectURL(img.src);
  8930. }
  8931. img.removeEventListener("load", loadHandler);
  8932. img.removeEventListener("error", errorHandler);
  8933. Tools.Error("Error while trying to load image: " + input);
  8934. if (onError) {
  8935. onError("Error while trying to load image: " + input, err);
  8936. }
  8937. };
  8938. img.addEventListener("load", loadHandler);
  8939. img.addEventListener("error", errorHandler);
  8940. var noIndexedDB = function () {
  8941. img.src = url;
  8942. };
  8943. var loadFromIndexedDB = function () {
  8944. if (database) {
  8945. database.loadImageFromDB(url, img);
  8946. }
  8947. };
  8948. //ANY database to do!
  8949. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8950. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8951. }
  8952. else {
  8953. if (url.indexOf("file:") !== -1) {
  8954. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8955. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8956. try {
  8957. var blobURL;
  8958. try {
  8959. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8960. }
  8961. catch (ex) {
  8962. // Chrome doesn't support oneTimeOnly parameter
  8963. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8964. }
  8965. img.src = blobURL;
  8966. usingObjectURL = true;
  8967. }
  8968. catch (e) {
  8969. img.src = "";
  8970. }
  8971. return img;
  8972. }
  8973. }
  8974. noIndexedDB();
  8975. }
  8976. return img;
  8977. };
  8978. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8979. url = Tools.CleanUrl(url);
  8980. url = Tools.PreprocessUrl(url);
  8981. // If file and file input are set
  8982. if (url.indexOf("file:") !== -1) {
  8983. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8984. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8985. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8986. }
  8987. }
  8988. var loadUrl = Tools.BaseUrl + url;
  8989. var aborted = false;
  8990. var fileRequest = {
  8991. onCompleteObservable: new BABYLON.Observable(),
  8992. abort: function () { return aborted = true; },
  8993. };
  8994. var requestFile = function () {
  8995. var request = new XMLHttpRequest();
  8996. var retryHandle = null;
  8997. fileRequest.abort = function () {
  8998. aborted = true;
  8999. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9000. request.abort();
  9001. }
  9002. if (retryHandle !== null) {
  9003. clearTimeout(retryHandle);
  9004. retryHandle = null;
  9005. }
  9006. };
  9007. var retryLoop = function (retryIndex) {
  9008. request.open('GET', loadUrl, true);
  9009. if (useArrayBuffer) {
  9010. request.responseType = "arraybuffer";
  9011. }
  9012. if (onProgress) {
  9013. request.addEventListener("progress", onProgress);
  9014. }
  9015. var onLoadEnd = function () {
  9016. request.removeEventListener("loadend", onLoadEnd);
  9017. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9018. fileRequest.onCompleteObservable.clear();
  9019. };
  9020. request.addEventListener("loadend", onLoadEnd);
  9021. var onReadyStateChange = function () {
  9022. if (aborted) {
  9023. return;
  9024. }
  9025. // In case of undefined state in some browsers.
  9026. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9027. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9028. request.removeEventListener("readystatechange", onReadyStateChange);
  9029. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9030. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9031. return;
  9032. }
  9033. var retryStrategy = Tools.DefaultRetryStrategy;
  9034. if (retryStrategy) {
  9035. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9036. if (waitTime !== -1) {
  9037. // Prevent the request from completing for retry.
  9038. request.removeEventListener("loadend", onLoadEnd);
  9039. request = new XMLHttpRequest();
  9040. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9041. return;
  9042. }
  9043. }
  9044. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9045. if (onError) {
  9046. onError(request, e);
  9047. }
  9048. else {
  9049. throw e;
  9050. }
  9051. }
  9052. };
  9053. request.addEventListener("readystatechange", onReadyStateChange);
  9054. request.send();
  9055. };
  9056. retryLoop(0);
  9057. };
  9058. // Caching all files
  9059. if (database && database.enableSceneOffline) {
  9060. var noIndexedDB_1 = function () {
  9061. if (!aborted) {
  9062. requestFile();
  9063. }
  9064. };
  9065. var loadFromIndexedDB = function () {
  9066. // TODO: database needs to support aborting and should return a IFileRequest
  9067. if (aborted) {
  9068. return;
  9069. }
  9070. if (database) {
  9071. database.loadFileFromDB(url, function (data) {
  9072. if (!aborted) {
  9073. onSuccess(data);
  9074. }
  9075. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9076. }, onProgress ? function (event) {
  9077. if (!aborted) {
  9078. onProgress(event);
  9079. }
  9080. } : undefined, noIndexedDB_1, useArrayBuffer);
  9081. }
  9082. };
  9083. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9084. }
  9085. else {
  9086. requestFile();
  9087. }
  9088. return fileRequest;
  9089. };
  9090. /**
  9091. * Load a script (identified by an url). When the url returns, the
  9092. * content of this file is added into a new script element, attached to the DOM (body element)
  9093. */
  9094. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9095. var head = document.getElementsByTagName('head')[0];
  9096. var script = document.createElement('script');
  9097. script.type = 'text/javascript';
  9098. script.src = scriptUrl;
  9099. script.onload = function () {
  9100. if (onSuccess) {
  9101. onSuccess();
  9102. }
  9103. };
  9104. script.onerror = function (e) {
  9105. if (onError) {
  9106. onError("Unable to load script '" + scriptUrl + "'", e);
  9107. }
  9108. };
  9109. head.appendChild(script);
  9110. };
  9111. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9112. var reader = new FileReader();
  9113. var request = {
  9114. onCompleteObservable: new BABYLON.Observable(),
  9115. abort: function () { return reader.abort(); },
  9116. };
  9117. reader.onloadend = function (e) {
  9118. request.onCompleteObservable.notifyObservers(request);
  9119. };
  9120. reader.onload = function (e) {
  9121. //target doesn't have result from ts 1.3
  9122. callback(e.target['result']);
  9123. };
  9124. reader.onprogress = progressCallback;
  9125. reader.readAsDataURL(fileToLoad);
  9126. return request;
  9127. };
  9128. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9129. var reader = new FileReader();
  9130. var request = {
  9131. onCompleteObservable: new BABYLON.Observable(),
  9132. abort: function () { return reader.abort(); },
  9133. };
  9134. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9135. reader.onerror = function (e) {
  9136. Tools.Log("Error while reading file: " + fileToLoad.name);
  9137. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9138. };
  9139. reader.onload = function (e) {
  9140. //target doesn't have result from ts 1.3
  9141. callback(e.target['result']);
  9142. };
  9143. if (progressCallBack) {
  9144. reader.onprogress = progressCallBack;
  9145. }
  9146. if (!useArrayBuffer) {
  9147. // Asynchronous read
  9148. reader.readAsText(fileToLoad);
  9149. }
  9150. else {
  9151. reader.readAsArrayBuffer(fileToLoad);
  9152. }
  9153. return request;
  9154. };
  9155. //returns a downloadable url to a file content.
  9156. Tools.FileAsURL = function (content) {
  9157. var fileBlob = new Blob([content]);
  9158. var url = window.URL || window.webkitURL;
  9159. var link = url.createObjectURL(fileBlob);
  9160. return link;
  9161. };
  9162. // Misc.
  9163. Tools.Format = function (value, decimals) {
  9164. if (decimals === void 0) { decimals = 2; }
  9165. return value.toFixed(decimals);
  9166. };
  9167. Tools.CheckExtends = function (v, min, max) {
  9168. if (v.x < min.x)
  9169. min.x = v.x;
  9170. if (v.y < min.y)
  9171. min.y = v.y;
  9172. if (v.z < min.z)
  9173. min.z = v.z;
  9174. if (v.x > max.x)
  9175. max.x = v.x;
  9176. if (v.y > max.y)
  9177. max.y = v.y;
  9178. if (v.z > max.z)
  9179. max.z = v.z;
  9180. };
  9181. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9182. for (var prop in source) {
  9183. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9184. continue;
  9185. }
  9186. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9187. continue;
  9188. }
  9189. var sourceValue = source[prop];
  9190. var typeOfSourceValue = typeof sourceValue;
  9191. if (typeOfSourceValue === "function") {
  9192. continue;
  9193. }
  9194. try {
  9195. if (typeOfSourceValue === "object") {
  9196. if (sourceValue instanceof Array) {
  9197. destination[prop] = [];
  9198. if (sourceValue.length > 0) {
  9199. if (typeof sourceValue[0] == "object") {
  9200. for (var index = 0; index < sourceValue.length; index++) {
  9201. var clonedValue = cloneValue(sourceValue[index], destination);
  9202. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9203. destination[prop].push(clonedValue);
  9204. }
  9205. }
  9206. }
  9207. else {
  9208. destination[prop] = sourceValue.slice(0);
  9209. }
  9210. }
  9211. }
  9212. else {
  9213. destination[prop] = cloneValue(sourceValue, destination);
  9214. }
  9215. }
  9216. else {
  9217. destination[prop] = sourceValue;
  9218. }
  9219. }
  9220. catch (e) {
  9221. // Just ignore error (it could be because of a read-only property)
  9222. }
  9223. }
  9224. };
  9225. Tools.IsEmpty = function (obj) {
  9226. for (var i in obj) {
  9227. if (obj.hasOwnProperty(i)) {
  9228. return false;
  9229. }
  9230. }
  9231. return true;
  9232. };
  9233. Tools.RegisterTopRootEvents = function (events) {
  9234. for (var index = 0; index < events.length; index++) {
  9235. var event = events[index];
  9236. window.addEventListener(event.name, event.handler, false);
  9237. try {
  9238. if (window.parent) {
  9239. window.parent.addEventListener(event.name, event.handler, false);
  9240. }
  9241. }
  9242. catch (e) {
  9243. // Silently fails...
  9244. }
  9245. }
  9246. };
  9247. Tools.UnregisterTopRootEvents = function (events) {
  9248. for (var index = 0; index < events.length; index++) {
  9249. var event = events[index];
  9250. window.removeEventListener(event.name, event.handler);
  9251. try {
  9252. if (window.parent) {
  9253. window.parent.removeEventListener(event.name, event.handler);
  9254. }
  9255. }
  9256. catch (e) {
  9257. // Silently fails...
  9258. }
  9259. }
  9260. };
  9261. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9262. if (mimeType === void 0) { mimeType = "image/png"; }
  9263. // Read the contents of the framebuffer
  9264. var numberOfChannelsByLine = width * 4;
  9265. var halfHeight = height / 2;
  9266. //Reading datas from WebGL
  9267. var data = engine.readPixels(0, 0, width, height);
  9268. //To flip image on Y axis.
  9269. for (var i = 0; i < halfHeight; i++) {
  9270. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9271. var currentCell = j + i * numberOfChannelsByLine;
  9272. var targetLine = height - i - 1;
  9273. var targetCell = j + targetLine * numberOfChannelsByLine;
  9274. var temp = data[currentCell];
  9275. data[currentCell] = data[targetCell];
  9276. data[targetCell] = temp;
  9277. }
  9278. }
  9279. // Create a 2D canvas to store the result
  9280. if (!screenshotCanvas) {
  9281. screenshotCanvas = document.createElement('canvas');
  9282. }
  9283. screenshotCanvas.width = width;
  9284. screenshotCanvas.height = height;
  9285. var context = screenshotCanvas.getContext('2d');
  9286. if (context) {
  9287. // Copy the pixels to a 2D canvas
  9288. var imageData = context.createImageData(width, height);
  9289. var castData = (imageData.data);
  9290. castData.set(data);
  9291. context.putImageData(imageData, 0, 0);
  9292. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9293. }
  9294. };
  9295. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9296. if (mimeType === void 0) { mimeType = "image/png"; }
  9297. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9298. if (successCallback) {
  9299. successCallback(base64Image);
  9300. }
  9301. else {
  9302. // We need HTMLCanvasElement.toBlob for HD screenshots
  9303. if (!screenshotCanvas.toBlob) {
  9304. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9305. screenshotCanvas.toBlob = function (callback, type, quality) {
  9306. var _this = this;
  9307. setTimeout(function () {
  9308. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9309. for (var i = 0; i < len; i++) {
  9310. arr[i] = binStr.charCodeAt(i);
  9311. }
  9312. callback(new Blob([arr], { type: type || 'image/png' }));
  9313. });
  9314. };
  9315. }
  9316. screenshotCanvas.toBlob(function (blob) {
  9317. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9318. if (("download" in document.createElement("a"))) {
  9319. if (!fileName) {
  9320. var date = new Date();
  9321. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9322. fileName = "screenshot_" + stringDate + ".png";
  9323. }
  9324. Tools.Download(blob, fileName);
  9325. }
  9326. else {
  9327. var url = URL.createObjectURL(blob);
  9328. var newWindow = window.open("");
  9329. if (!newWindow)
  9330. return;
  9331. var img = newWindow.document.createElement("img");
  9332. img.onload = function () {
  9333. // no longer need to read the blob so it's revoked
  9334. URL.revokeObjectURL(url);
  9335. };
  9336. img.src = url;
  9337. newWindow.document.body.appendChild(img);
  9338. }
  9339. });
  9340. }
  9341. };
  9342. /**
  9343. * Downloads a blob in the browser
  9344. * @param blob defines the blob to download
  9345. * @param fileName defines the name of the downloaded file
  9346. */
  9347. Tools.Download = function (blob, fileName) {
  9348. var url = window.URL.createObjectURL(blob);
  9349. var a = document.createElement("a");
  9350. document.body.appendChild(a);
  9351. a.style.display = "none";
  9352. a.href = url;
  9353. a.download = fileName;
  9354. a.addEventListener("click", function () {
  9355. if (a.parentElement) {
  9356. a.parentElement.removeChild(a);
  9357. }
  9358. });
  9359. a.click();
  9360. window.URL.revokeObjectURL(url);
  9361. };
  9362. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9363. if (mimeType === void 0) { mimeType = "image/png"; }
  9364. var width;
  9365. var height;
  9366. // If a precision value is specified
  9367. if (size.precision) {
  9368. width = Math.round(engine.getRenderWidth() * size.precision);
  9369. height = Math.round(width / engine.getAspectRatio(camera));
  9370. }
  9371. else if (size.width && size.height) {
  9372. width = size.width;
  9373. height = size.height;
  9374. }
  9375. //If passing only width, computing height to keep display canvas ratio.
  9376. else if (size.width && !size.height) {
  9377. width = size.width;
  9378. height = Math.round(width / engine.getAspectRatio(camera));
  9379. }
  9380. //If passing only height, computing width to keep display canvas ratio.
  9381. else if (size.height && !size.width) {
  9382. height = size.height;
  9383. width = Math.round(height * engine.getAspectRatio(camera));
  9384. }
  9385. //Assuming here that "size" parameter is a number
  9386. else if (!isNaN(size)) {
  9387. height = size;
  9388. width = size;
  9389. }
  9390. else {
  9391. Tools.Error("Invalid 'size' parameter !");
  9392. return;
  9393. }
  9394. if (!screenshotCanvas) {
  9395. screenshotCanvas = document.createElement('canvas');
  9396. }
  9397. screenshotCanvas.width = width;
  9398. screenshotCanvas.height = height;
  9399. var renderContext = screenshotCanvas.getContext("2d");
  9400. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9401. var newWidth = width;
  9402. var newHeight = newWidth / ratio;
  9403. if (newHeight > height) {
  9404. newHeight = height;
  9405. newWidth = newHeight * ratio;
  9406. }
  9407. var offsetX = Math.max(0, width - newWidth) / 2;
  9408. var offsetY = Math.max(0, height - newHeight) / 2;
  9409. var renderingCanvas = engine.getRenderingCanvas();
  9410. if (renderContext && renderingCanvas) {
  9411. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9412. }
  9413. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9414. };
  9415. /**
  9416. * Generates an image screenshot from the specified camera.
  9417. *
  9418. * @param engine The engine to use for rendering
  9419. * @param camera The camera to use for rendering
  9420. * @param size This parameter can be set to a single number or to an object with the
  9421. * following (optional) properties: precision, width, height. If a single number is passed,
  9422. * it will be used for both width and height. If an object is passed, the screenshot size
  9423. * will be derived from the parameters. The precision property is a multiplier allowing
  9424. * rendering at a higher or lower resolution.
  9425. * @param successCallback The callback receives a single parameter which contains the
  9426. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9427. * src parameter of an <img> to display it.
  9428. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9429. * Check your browser for supported MIME types.
  9430. * @param samples Texture samples (default: 1)
  9431. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9432. * @param fileName A name for for the downloaded file.
  9433. * @constructor
  9434. */
  9435. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9436. if (mimeType === void 0) { mimeType = "image/png"; }
  9437. if (samples === void 0) { samples = 1; }
  9438. if (antialiasing === void 0) { antialiasing = false; }
  9439. var width;
  9440. var height;
  9441. //If a precision value is specified
  9442. if (size.precision) {
  9443. width = Math.round(engine.getRenderWidth() * size.precision);
  9444. height = Math.round(width / engine.getAspectRatio(camera));
  9445. size = { width: width, height: height };
  9446. }
  9447. else if (size.width && size.height) {
  9448. width = size.width;
  9449. height = size.height;
  9450. }
  9451. //If passing only width, computing height to keep display canvas ratio.
  9452. else if (size.width && !size.height) {
  9453. width = size.width;
  9454. height = Math.round(width / engine.getAspectRatio(camera));
  9455. size = { width: width, height: height };
  9456. }
  9457. //If passing only height, computing width to keep display canvas ratio.
  9458. else if (size.height && !size.width) {
  9459. height = size.height;
  9460. width = Math.round(height * engine.getAspectRatio(camera));
  9461. size = { width: width, height: height };
  9462. }
  9463. //Assuming here that "size" parameter is a number
  9464. else if (!isNaN(size)) {
  9465. height = size;
  9466. width = size;
  9467. }
  9468. else {
  9469. Tools.Error("Invalid 'size' parameter !");
  9470. return;
  9471. }
  9472. var scene = camera.getScene();
  9473. var previousCamera = null;
  9474. if (scene.activeCamera !== camera) {
  9475. previousCamera = scene.activeCamera;
  9476. scene.activeCamera = camera;
  9477. }
  9478. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9479. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9480. texture.renderList = null;
  9481. texture.samples = samples;
  9482. if (antialiasing) {
  9483. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9484. }
  9485. texture.onAfterRenderObservable.add(function () {
  9486. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9487. });
  9488. scene.incrementRenderId();
  9489. scene.resetCachedMaterial();
  9490. texture.render(true);
  9491. texture.dispose();
  9492. if (previousCamera) {
  9493. scene.activeCamera = previousCamera;
  9494. }
  9495. camera.getProjectionMatrix(true); // Force cache refresh;
  9496. };
  9497. // XHR response validator for local file scenario
  9498. Tools.ValidateXHRData = function (xhr, dataType) {
  9499. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9500. if (dataType === void 0) { dataType = 7; }
  9501. try {
  9502. if (dataType & 1) {
  9503. if (xhr.responseText && xhr.responseText.length > 0) {
  9504. return true;
  9505. }
  9506. else if (dataType === 1) {
  9507. return false;
  9508. }
  9509. }
  9510. if (dataType & 2) {
  9511. // Check header width and height since there is no "TGA" magic number
  9512. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9513. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9514. return true;
  9515. }
  9516. else if (dataType === 2) {
  9517. return false;
  9518. }
  9519. }
  9520. if (dataType & 4) {
  9521. // Check for the "DDS" magic number
  9522. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9523. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9524. return true;
  9525. }
  9526. else {
  9527. return false;
  9528. }
  9529. }
  9530. }
  9531. catch (e) {
  9532. // Global protection
  9533. }
  9534. return false;
  9535. };
  9536. /**
  9537. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9538. * Be aware Math.random() could cause collisions, but:
  9539. * "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"
  9540. */
  9541. Tools.RandomId = function () {
  9542. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9543. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9544. return v.toString(16);
  9545. });
  9546. };
  9547. /**
  9548. * Test if the given uri is a base64 string.
  9549. * @param uri The uri to test
  9550. * @return True if the uri is a base64 string or false otherwise.
  9551. */
  9552. Tools.IsBase64 = function (uri) {
  9553. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9554. };
  9555. /**
  9556. * Decode the given base64 uri.
  9557. * @param uri The uri to decode
  9558. * @return The decoded base64 data.
  9559. */
  9560. Tools.DecodeBase64 = function (uri) {
  9561. var decodedString = atob(uri.split(",")[1]);
  9562. var bufferLength = decodedString.length;
  9563. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9564. for (var i = 0; i < bufferLength; i++) {
  9565. bufferView[i] = decodedString.charCodeAt(i);
  9566. }
  9567. return bufferView.buffer;
  9568. };
  9569. Object.defineProperty(Tools, "NoneLogLevel", {
  9570. get: function () {
  9571. return Tools._NoneLogLevel;
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(Tools, "MessageLogLevel", {
  9577. get: function () {
  9578. return Tools._MessageLogLevel;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Object.defineProperty(Tools, "WarningLogLevel", {
  9584. get: function () {
  9585. return Tools._WarningLogLevel;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(Tools, "ErrorLogLevel", {
  9591. get: function () {
  9592. return Tools._ErrorLogLevel;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(Tools, "AllLogLevel", {
  9598. get: function () {
  9599. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Tools._AddLogEntry = function (entry) {
  9605. Tools._LogCache = entry + Tools._LogCache;
  9606. if (Tools.OnNewCacheEntry) {
  9607. Tools.OnNewCacheEntry(entry);
  9608. }
  9609. };
  9610. Tools._FormatMessage = function (message) {
  9611. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9612. var date = new Date();
  9613. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9614. };
  9615. Tools._LogDisabled = function (message) {
  9616. // nothing to do
  9617. };
  9618. Tools._LogEnabled = function (message) {
  9619. var formattedMessage = Tools._FormatMessage(message);
  9620. console.log("BJS - " + formattedMessage);
  9621. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9622. Tools._AddLogEntry(entry);
  9623. };
  9624. Tools._WarnDisabled = function (message) {
  9625. // nothing to do
  9626. };
  9627. Tools._WarnEnabled = function (message) {
  9628. var formattedMessage = Tools._FormatMessage(message);
  9629. console.warn("BJS - " + formattedMessage);
  9630. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9631. Tools._AddLogEntry(entry);
  9632. };
  9633. Tools._ErrorDisabled = function (message) {
  9634. // nothing to do
  9635. };
  9636. Tools._ErrorEnabled = function (message) {
  9637. Tools.errorsCount++;
  9638. var formattedMessage = Tools._FormatMessage(message);
  9639. console.error("BJS - " + formattedMessage);
  9640. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9641. Tools._AddLogEntry(entry);
  9642. };
  9643. Object.defineProperty(Tools, "LogCache", {
  9644. get: function () {
  9645. return Tools._LogCache;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. Tools.ClearLogCache = function () {
  9651. Tools._LogCache = "";
  9652. Tools.errorsCount = 0;
  9653. };
  9654. Object.defineProperty(Tools, "LogLevels", {
  9655. set: function (level) {
  9656. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9657. Tools.Log = Tools._LogEnabled;
  9658. }
  9659. else {
  9660. Tools.Log = Tools._LogDisabled;
  9661. }
  9662. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9663. Tools.Warn = Tools._WarnEnabled;
  9664. }
  9665. else {
  9666. Tools.Warn = Tools._WarnDisabled;
  9667. }
  9668. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9669. Tools.Error = Tools._ErrorEnabled;
  9670. }
  9671. else {
  9672. Tools.Error = Tools._ErrorDisabled;
  9673. }
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Tools.IsWindowObjectExist = function () {
  9679. return (typeof window) !== "undefined";
  9680. };
  9681. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9682. get: function () {
  9683. return Tools._PerformanceNoneLogLevel;
  9684. },
  9685. enumerable: true,
  9686. configurable: true
  9687. });
  9688. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9689. get: function () {
  9690. return Tools._PerformanceUserMarkLogLevel;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9696. get: function () {
  9697. return Tools._PerformanceConsoleLogLevel;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9703. set: function (level) {
  9704. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9705. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9706. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9707. return;
  9708. }
  9709. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9710. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9711. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9712. return;
  9713. }
  9714. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9715. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9721. };
  9722. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9723. };
  9724. Tools._StartUserMark = function (counterName, condition) {
  9725. if (condition === void 0) { condition = true; }
  9726. if (!Tools._performance) {
  9727. if (!Tools.IsWindowObjectExist()) {
  9728. return;
  9729. }
  9730. Tools._performance = window.performance;
  9731. }
  9732. if (!condition || !Tools._performance.mark) {
  9733. return;
  9734. }
  9735. Tools._performance.mark(counterName + "-Begin");
  9736. };
  9737. Tools._EndUserMark = function (counterName, condition) {
  9738. if (condition === void 0) { condition = true; }
  9739. if (!condition || !Tools._performance.mark) {
  9740. return;
  9741. }
  9742. Tools._performance.mark(counterName + "-End");
  9743. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9744. };
  9745. Tools._StartPerformanceConsole = function (counterName, condition) {
  9746. if (condition === void 0) { condition = true; }
  9747. if (!condition) {
  9748. return;
  9749. }
  9750. Tools._StartUserMark(counterName, condition);
  9751. if (console.time) {
  9752. console.time(counterName);
  9753. }
  9754. };
  9755. Tools._EndPerformanceConsole = function (counterName, condition) {
  9756. if (condition === void 0) { condition = true; }
  9757. if (!condition) {
  9758. return;
  9759. }
  9760. Tools._EndUserMark(counterName, condition);
  9761. if (console.time) {
  9762. console.timeEnd(counterName);
  9763. }
  9764. };
  9765. Object.defineProperty(Tools, "Now", {
  9766. get: function () {
  9767. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9768. return window.performance.now();
  9769. }
  9770. return Date.now();
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. /**
  9776. * This method will return the name of the class used to create the instance of the given object.
  9777. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9778. * @param object the object to get the class name from
  9779. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9780. */
  9781. Tools.GetClassName = function (object, isType) {
  9782. if (isType === void 0) { isType = false; }
  9783. var name = null;
  9784. if (!isType && object.getClassName) {
  9785. name = object.getClassName();
  9786. }
  9787. else {
  9788. if (object instanceof Object) {
  9789. var classObj = isType ? object : Object.getPrototypeOf(object);
  9790. name = classObj.constructor["__bjsclassName__"];
  9791. }
  9792. if (!name) {
  9793. name = typeof object;
  9794. }
  9795. }
  9796. return name;
  9797. };
  9798. Tools.First = function (array, predicate) {
  9799. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9800. var el = array_1[_i];
  9801. if (predicate(el)) {
  9802. return el;
  9803. }
  9804. }
  9805. return null;
  9806. };
  9807. /**
  9808. * This method will return the name of the full name of the class, including its owning module (if any).
  9809. * 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).
  9810. * @param object the object to get the class name from
  9811. * @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.
  9812. */
  9813. Tools.getFullClassName = function (object, isType) {
  9814. if (isType === void 0) { isType = false; }
  9815. var className = null;
  9816. var moduleName = null;
  9817. if (!isType && object.getClassName) {
  9818. className = object.getClassName();
  9819. }
  9820. else {
  9821. if (object instanceof Object) {
  9822. var classObj = isType ? object : Object.getPrototypeOf(object);
  9823. className = classObj.constructor["__bjsclassName__"];
  9824. moduleName = classObj.constructor["__bjsmoduleName__"];
  9825. }
  9826. if (!className) {
  9827. className = typeof object;
  9828. }
  9829. }
  9830. if (!className) {
  9831. return null;
  9832. }
  9833. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9834. };
  9835. /**
  9836. * 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.
  9837. * @param array
  9838. */
  9839. Tools.arrayOrStringFeeder = function (array) {
  9840. return function (index) {
  9841. if (index >= array.length) {
  9842. return null;
  9843. }
  9844. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9845. if (val && val.getHashCode) {
  9846. val = val.getHashCode();
  9847. }
  9848. if (typeof val === "string") {
  9849. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9850. }
  9851. return val;
  9852. };
  9853. };
  9854. /**
  9855. * Compute the hashCode of a stream of number
  9856. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9857. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9858. * @return the hash code computed
  9859. */
  9860. Tools.hashCodeFromStream = function (feeder) {
  9861. // Based from here: http://stackoverflow.com/a/7616484/802124
  9862. var hash = 0;
  9863. var index = 0;
  9864. var chr = feeder(index++);
  9865. while (chr != null) {
  9866. hash = ((hash << 5) - hash) + chr;
  9867. hash |= 0; // Convert to 32bit integer
  9868. chr = feeder(index++);
  9869. }
  9870. return hash;
  9871. };
  9872. /**
  9873. * Returns a promise that resolves after the given amount of time.
  9874. * @param delay Number of milliseconds to delay
  9875. * @returns Promise that resolves after the given amount of time
  9876. */
  9877. Tools.DelayAsync = function (delay) {
  9878. return new Promise(function (resolve) {
  9879. setTimeout(function () {
  9880. resolve();
  9881. }, delay);
  9882. });
  9883. };
  9884. Tools.BaseUrl = "";
  9885. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9886. /**
  9887. * Default behaviour for cors in the application.
  9888. * It can be a string if the expected behavior is identical in the entire app.
  9889. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9890. */
  9891. Tools.CorsBehavior = "anonymous";
  9892. Tools.UseFallbackTexture = true;
  9893. /**
  9894. * Use this object to register external classes like custom textures or material
  9895. * to allow the laoders to instantiate them
  9896. */
  9897. Tools.RegisteredExternalClasses = {};
  9898. // Used in case of a texture loading problem
  9899. 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";
  9900. Tools._tmpFloatArray = new Float32Array(1);
  9901. Tools.PreprocessUrl = function (url) {
  9902. return url;
  9903. };
  9904. // Logs
  9905. Tools._NoneLogLevel = 0;
  9906. Tools._MessageLogLevel = 1;
  9907. Tools._WarningLogLevel = 2;
  9908. Tools._ErrorLogLevel = 4;
  9909. Tools._LogCache = "";
  9910. Tools.errorsCount = 0;
  9911. Tools.Log = Tools._LogEnabled;
  9912. Tools.Warn = Tools._WarnEnabled;
  9913. Tools.Error = Tools._ErrorEnabled;
  9914. // Performances
  9915. Tools._PerformanceNoneLogLevel = 0;
  9916. Tools._PerformanceUserMarkLogLevel = 1;
  9917. Tools._PerformanceConsoleLogLevel = 2;
  9918. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9919. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9920. return Tools;
  9921. }());
  9922. BABYLON.Tools = Tools;
  9923. /**
  9924. * This class is used to track a performance counter which is number based.
  9925. * The user has access to many properties which give statistics of different nature
  9926. *
  9927. * The implementer can track two kinds of Performance Counter: time and count
  9928. * 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.
  9929. * 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.
  9930. */
  9931. var PerfCounter = /** @class */ (function () {
  9932. function PerfCounter() {
  9933. this._startMonitoringTime = 0;
  9934. this._min = 0;
  9935. this._max = 0;
  9936. this._average = 0;
  9937. this._lastSecAverage = 0;
  9938. this._current = 0;
  9939. this._totalValueCount = 0;
  9940. this._totalAccumulated = 0;
  9941. this._lastSecAccumulated = 0;
  9942. this._lastSecTime = 0;
  9943. this._lastSecValueCount = 0;
  9944. }
  9945. Object.defineProperty(PerfCounter.prototype, "min", {
  9946. /**
  9947. * Returns the smallest value ever
  9948. */
  9949. get: function () {
  9950. return this._min;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(PerfCounter.prototype, "max", {
  9956. /**
  9957. * Returns the biggest value ever
  9958. */
  9959. get: function () {
  9960. return this._max;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(PerfCounter.prototype, "average", {
  9966. /**
  9967. * Returns the average value since the performance counter is running
  9968. */
  9969. get: function () {
  9970. return this._average;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9976. /**
  9977. * Returns the average value of the last second the counter was monitored
  9978. */
  9979. get: function () {
  9980. return this._lastSecAverage;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(PerfCounter.prototype, "current", {
  9986. /**
  9987. * Returns the current value
  9988. */
  9989. get: function () {
  9990. return this._current;
  9991. },
  9992. enumerable: true,
  9993. configurable: true
  9994. });
  9995. Object.defineProperty(PerfCounter.prototype, "total", {
  9996. get: function () {
  9997. return this._totalAccumulated;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Object.defineProperty(PerfCounter.prototype, "count", {
  10003. get: function () {
  10004. return this._totalValueCount;
  10005. },
  10006. enumerable: true,
  10007. configurable: true
  10008. });
  10009. /**
  10010. * Call this method to start monitoring a new frame.
  10011. * 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.
  10012. */
  10013. PerfCounter.prototype.fetchNewFrame = function () {
  10014. this._totalValueCount++;
  10015. this._current = 0;
  10016. this._lastSecValueCount++;
  10017. };
  10018. /**
  10019. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10020. * @param newCount the count value to add to the monitored count
  10021. * @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.
  10022. */
  10023. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10024. if (!PerfCounter.Enabled) {
  10025. return;
  10026. }
  10027. this._current += newCount;
  10028. if (fetchResult) {
  10029. this._fetchResult();
  10030. }
  10031. };
  10032. /**
  10033. * Start monitoring this performance counter
  10034. */
  10035. PerfCounter.prototype.beginMonitoring = function () {
  10036. if (!PerfCounter.Enabled) {
  10037. return;
  10038. }
  10039. this._startMonitoringTime = Tools.Now;
  10040. };
  10041. /**
  10042. * Compute the time lapsed since the previous beginMonitoring() call.
  10043. * @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
  10044. */
  10045. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10046. if (newFrame === void 0) { newFrame = true; }
  10047. if (!PerfCounter.Enabled) {
  10048. return;
  10049. }
  10050. if (newFrame) {
  10051. this.fetchNewFrame();
  10052. }
  10053. var currentTime = Tools.Now;
  10054. this._current = currentTime - this._startMonitoringTime;
  10055. if (newFrame) {
  10056. this._fetchResult();
  10057. }
  10058. };
  10059. PerfCounter.prototype._fetchResult = function () {
  10060. this._totalAccumulated += this._current;
  10061. this._lastSecAccumulated += this._current;
  10062. // Min/Max update
  10063. this._min = Math.min(this._min, this._current);
  10064. this._max = Math.max(this._max, this._current);
  10065. this._average = this._totalAccumulated / this._totalValueCount;
  10066. // Reset last sec?
  10067. var now = Tools.Now;
  10068. if ((now - this._lastSecTime) > 1000) {
  10069. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10070. this._lastSecTime = now;
  10071. this._lastSecAccumulated = 0;
  10072. this._lastSecValueCount = 0;
  10073. }
  10074. };
  10075. PerfCounter.Enabled = true;
  10076. return PerfCounter;
  10077. }());
  10078. BABYLON.PerfCounter = PerfCounter;
  10079. /**
  10080. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10081. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10082. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10083. * @param name The name of the class, case should be preserved
  10084. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10085. */
  10086. function className(name, module) {
  10087. return function (target) {
  10088. target["__bjsclassName__"] = name;
  10089. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10090. };
  10091. }
  10092. BABYLON.className = className;
  10093. /**
  10094. * An implementation of a loop for asynchronous functions.
  10095. */
  10096. var AsyncLoop = /** @class */ (function () {
  10097. /**
  10098. * Constroctor.
  10099. * @param iterations the number of iterations.
  10100. * @param _fn the function to run each iteration
  10101. * @param _successCallback the callback that will be called upon succesful execution
  10102. * @param offset starting offset.
  10103. */
  10104. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10105. if (offset === void 0) { offset = 0; }
  10106. this.iterations = iterations;
  10107. this._fn = _fn;
  10108. this._successCallback = _successCallback;
  10109. this.index = offset - 1;
  10110. this._done = false;
  10111. }
  10112. /**
  10113. * Execute the next iteration. Must be called after the last iteration was finished.
  10114. */
  10115. AsyncLoop.prototype.executeNext = function () {
  10116. if (!this._done) {
  10117. if (this.index + 1 < this.iterations) {
  10118. ++this.index;
  10119. this._fn(this);
  10120. }
  10121. else {
  10122. this.breakLoop();
  10123. }
  10124. }
  10125. };
  10126. /**
  10127. * Break the loop and run the success callback.
  10128. */
  10129. AsyncLoop.prototype.breakLoop = function () {
  10130. this._done = true;
  10131. this._successCallback();
  10132. };
  10133. /**
  10134. * Helper function
  10135. */
  10136. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10137. if (offset === void 0) { offset = 0; }
  10138. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10139. loop.executeNext();
  10140. return loop;
  10141. };
  10142. /**
  10143. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10144. * @param iterations total number of iterations
  10145. * @param syncedIterations number of synchronous iterations in each async iteration.
  10146. * @param fn the function to call each iteration.
  10147. * @param callback a success call back that will be called when iterating stops.
  10148. * @param breakFunction a break condition (optional)
  10149. * @param timeout timeout settings for the setTimeout function. default - 0.
  10150. * @constructor
  10151. */
  10152. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10153. if (timeout === void 0) { timeout = 0; }
  10154. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10155. if (breakFunction && breakFunction())
  10156. loop.breakLoop();
  10157. else {
  10158. setTimeout(function () {
  10159. for (var i = 0; i < syncedIterations; ++i) {
  10160. var iteration = (loop.index * syncedIterations) + i;
  10161. if (iteration >= iterations)
  10162. break;
  10163. fn(iteration);
  10164. if (breakFunction && breakFunction()) {
  10165. loop.breakLoop();
  10166. break;
  10167. }
  10168. }
  10169. loop.executeNext();
  10170. }, timeout);
  10171. }
  10172. }, callback);
  10173. };
  10174. return AsyncLoop;
  10175. }());
  10176. BABYLON.AsyncLoop = AsyncLoop;
  10177. })(BABYLON || (BABYLON = {}));
  10178. //# sourceMappingURL=babylon.tools.js.map
  10179. var BABYLON;
  10180. (function (BABYLON) {
  10181. var PromiseStates;
  10182. (function (PromiseStates) {
  10183. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10184. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10185. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10186. })(PromiseStates || (PromiseStates = {}));
  10187. var FulFillmentAgregator = /** @class */ (function () {
  10188. function FulFillmentAgregator() {
  10189. this.count = 0;
  10190. this.target = 0;
  10191. this.results = [];
  10192. }
  10193. return FulFillmentAgregator;
  10194. }());
  10195. var InternalPromise = /** @class */ (function () {
  10196. function InternalPromise(resolver) {
  10197. var _this = this;
  10198. this._state = PromiseStates.Pending;
  10199. this._children = new Array();
  10200. this._rejectWasConsumed = false;
  10201. if (!resolver) {
  10202. return;
  10203. }
  10204. try {
  10205. resolver(function (value) {
  10206. _this._resolve(value);
  10207. }, function (reason) {
  10208. _this._reject(reason);
  10209. });
  10210. }
  10211. catch (e) {
  10212. this._reject(e);
  10213. }
  10214. }
  10215. Object.defineProperty(InternalPromise.prototype, "_result", {
  10216. get: function () {
  10217. return this._resultValue;
  10218. },
  10219. set: function (value) {
  10220. this._resultValue = value;
  10221. if (this._parent && this._parent._result === undefined) {
  10222. this._parent._result = value;
  10223. }
  10224. },
  10225. enumerable: true,
  10226. configurable: true
  10227. });
  10228. InternalPromise.prototype.catch = function (onRejected) {
  10229. return this.then(undefined, onRejected);
  10230. };
  10231. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10232. var _this = this;
  10233. var newPromise = new InternalPromise();
  10234. newPromise._onFulfilled = onFulfilled;
  10235. newPromise._onRejected = onRejected;
  10236. // Composition
  10237. this._children.push(newPromise);
  10238. newPromise._parent = this;
  10239. if (this._state !== PromiseStates.Pending) {
  10240. BABYLON.Tools.SetImmediate(function () {
  10241. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10242. var returnedValue = newPromise._resolve(_this._result);
  10243. if (returnedValue !== undefined && returnedValue !== null) {
  10244. if (returnedValue._state !== undefined) {
  10245. var returnedPromise = returnedValue;
  10246. newPromise._children.push(returnedPromise);
  10247. returnedPromise._parent = newPromise;
  10248. newPromise = returnedPromise;
  10249. }
  10250. else {
  10251. newPromise._result = returnedValue;
  10252. }
  10253. }
  10254. }
  10255. else {
  10256. newPromise._reject(_this._reason);
  10257. }
  10258. });
  10259. }
  10260. return newPromise;
  10261. };
  10262. InternalPromise.prototype._moveChildren = function (children) {
  10263. var _this = this;
  10264. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10265. this._children.forEach(function (child) {
  10266. child._parent = _this;
  10267. });
  10268. if (this._state === PromiseStates.Fulfilled) {
  10269. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10270. var child = _b[_i];
  10271. child._resolve(this._result);
  10272. }
  10273. }
  10274. else if (this._state === PromiseStates.Rejected) {
  10275. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10276. var child = _d[_c];
  10277. child._reject(this._reason);
  10278. }
  10279. }
  10280. var _a;
  10281. };
  10282. InternalPromise.prototype._resolve = function (value) {
  10283. try {
  10284. this._state = PromiseStates.Fulfilled;
  10285. var returnedValue = null;
  10286. if (this._onFulfilled) {
  10287. returnedValue = this._onFulfilled(value);
  10288. }
  10289. if (returnedValue !== undefined && returnedValue !== null) {
  10290. if (returnedValue._state !== undefined) {
  10291. // Transmit children
  10292. var returnedPromise = returnedValue;
  10293. returnedPromise._parent = this;
  10294. returnedPromise._moveChildren(this._children);
  10295. value = returnedPromise._result;
  10296. }
  10297. else {
  10298. value = returnedValue;
  10299. }
  10300. }
  10301. this._result = value;
  10302. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10303. var child = _a[_i];
  10304. child._resolve(value);
  10305. }
  10306. this._children.length = 0;
  10307. delete this._onFulfilled;
  10308. delete this._onRejected;
  10309. }
  10310. catch (e) {
  10311. this._reject(e, true);
  10312. }
  10313. };
  10314. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10315. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10316. this._state = PromiseStates.Rejected;
  10317. this._reason = reason;
  10318. if (this._onRejected && !onLocalThrow) {
  10319. try {
  10320. this._onRejected(reason);
  10321. this._rejectWasConsumed = true;
  10322. }
  10323. catch (e) {
  10324. reason = e;
  10325. }
  10326. }
  10327. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10328. var child = _a[_i];
  10329. if (this._rejectWasConsumed) {
  10330. child._resolve(null);
  10331. }
  10332. else {
  10333. child._reject(reason);
  10334. }
  10335. }
  10336. this._children.length = 0;
  10337. delete this._onFulfilled;
  10338. delete this._onRejected;
  10339. };
  10340. InternalPromise.resolve = function (value) {
  10341. var newPromise = new InternalPromise();
  10342. newPromise._resolve(value);
  10343. return newPromise;
  10344. };
  10345. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10346. promise.then(function (value) {
  10347. agregator.results[index] = value;
  10348. agregator.count++;
  10349. if (agregator.count === agregator.target) {
  10350. agregator.rootPromise._resolve(agregator.results);
  10351. }
  10352. return null;
  10353. }, function (reason) {
  10354. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10355. agregator.rootPromise._reject(reason);
  10356. }
  10357. });
  10358. };
  10359. InternalPromise.all = function (promises) {
  10360. var newPromise = new InternalPromise();
  10361. var agregator = new FulFillmentAgregator();
  10362. agregator.target = promises.length;
  10363. agregator.rootPromise = newPromise;
  10364. if (promises.length) {
  10365. for (var index = 0; index < promises.length; index++) {
  10366. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10367. }
  10368. }
  10369. else {
  10370. newPromise._resolve([]);
  10371. }
  10372. return newPromise;
  10373. };
  10374. InternalPromise.race = function (promises) {
  10375. var newPromise = new InternalPromise();
  10376. if (promises.length) {
  10377. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10378. var promise = promises_1[_i];
  10379. promise.then(function (value) {
  10380. if (newPromise) {
  10381. newPromise._resolve(value);
  10382. newPromise = null;
  10383. }
  10384. return null;
  10385. }, function (reason) {
  10386. if (newPromise) {
  10387. newPromise._reject(reason);
  10388. newPromise = null;
  10389. }
  10390. });
  10391. }
  10392. }
  10393. return newPromise;
  10394. };
  10395. return InternalPromise;
  10396. }());
  10397. /**
  10398. * Helper class that provides a small promise polyfill
  10399. */
  10400. var PromisePolyfill = /** @class */ (function () {
  10401. function PromisePolyfill() {
  10402. }
  10403. /**
  10404. * Static function used to check if the polyfill is required
  10405. * If this is the case then the function will inject the polyfill to window.Promise
  10406. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10407. */
  10408. PromisePolyfill.Apply = function (force) {
  10409. if (force === void 0) { force = false; }
  10410. if (force || typeof Promise === 'undefined') {
  10411. var root = window;
  10412. root.Promise = InternalPromise;
  10413. }
  10414. };
  10415. return PromisePolyfill;
  10416. }());
  10417. BABYLON.PromisePolyfill = PromisePolyfill;
  10418. })(BABYLON || (BABYLON = {}));
  10419. //# sourceMappingURL=babylon.promise.js.map
  10420. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10421. var BABYLON;
  10422. (function (BABYLON) {
  10423. /**
  10424. * Helper class to push actions to a pool of workers.
  10425. */
  10426. var WorkerPool = /** @class */ (function () {
  10427. /**
  10428. * Constructor
  10429. * @param workers Array of workers to use for actions
  10430. */
  10431. function WorkerPool(workers) {
  10432. this._pendingActions = new Array();
  10433. this._workerInfos = workers.map(function (worker) { return ({
  10434. worker: worker,
  10435. active: false
  10436. }); });
  10437. }
  10438. /**
  10439. * Terminates all workers and clears any pending actions.
  10440. */
  10441. WorkerPool.prototype.dispose = function () {
  10442. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10443. var workerInfo = _a[_i];
  10444. workerInfo.worker.terminate();
  10445. }
  10446. delete this._workerInfos;
  10447. delete this._pendingActions;
  10448. };
  10449. /**
  10450. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10451. * pended until a worker has completed its action.
  10452. * @param action The action to perform. Call onComplete when the action is complete.
  10453. */
  10454. WorkerPool.prototype.push = function (action) {
  10455. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10456. var workerInfo = _a[_i];
  10457. if (!workerInfo.active) {
  10458. this._execute(workerInfo, action);
  10459. return;
  10460. }
  10461. }
  10462. this._pendingActions.push(action);
  10463. };
  10464. WorkerPool.prototype._execute = function (workerInfo, action) {
  10465. var _this = this;
  10466. workerInfo.active = true;
  10467. action(workerInfo.worker, function () {
  10468. workerInfo.active = false;
  10469. var nextAction = _this._pendingActions.shift();
  10470. if (nextAction) {
  10471. _this._execute(workerInfo, nextAction);
  10472. }
  10473. });
  10474. };
  10475. return WorkerPool;
  10476. }());
  10477. BABYLON.WorkerPool = WorkerPool;
  10478. })(BABYLON || (BABYLON = {}));
  10479. //# sourceMappingURL=babylon.workerPool.js.map
  10480. var BABYLON;
  10481. (function (BABYLON) {
  10482. /**
  10483. * @hidden
  10484. **/
  10485. var _AlphaState = /** @class */ (function () {
  10486. /**
  10487. * Initializes the state.
  10488. */
  10489. function _AlphaState() {
  10490. this._isAlphaBlendDirty = false;
  10491. this._isBlendFunctionParametersDirty = false;
  10492. this._isBlendEquationParametersDirty = false;
  10493. this._isBlendConstantsDirty = false;
  10494. this._alphaBlend = false;
  10495. this._blendFunctionParameters = new Array(4);
  10496. this._blendEquationParameters = new Array(2);
  10497. this._blendConstants = new Array(4);
  10498. this.reset();
  10499. }
  10500. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10501. get: function () {
  10502. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10503. },
  10504. enumerable: true,
  10505. configurable: true
  10506. });
  10507. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10508. get: function () {
  10509. return this._alphaBlend;
  10510. },
  10511. set: function (value) {
  10512. if (this._alphaBlend === value) {
  10513. return;
  10514. }
  10515. this._alphaBlend = value;
  10516. this._isAlphaBlendDirty = true;
  10517. },
  10518. enumerable: true,
  10519. configurable: true
  10520. });
  10521. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10522. if (this._blendConstants[0] === r &&
  10523. this._blendConstants[1] === g &&
  10524. this._blendConstants[2] === b &&
  10525. this._blendConstants[3] === a) {
  10526. return;
  10527. }
  10528. this._blendConstants[0] = r;
  10529. this._blendConstants[1] = g;
  10530. this._blendConstants[2] = b;
  10531. this._blendConstants[3] = a;
  10532. this._isBlendConstantsDirty = true;
  10533. };
  10534. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10535. if (this._blendFunctionParameters[0] === value0 &&
  10536. this._blendFunctionParameters[1] === value1 &&
  10537. this._blendFunctionParameters[2] === value2 &&
  10538. this._blendFunctionParameters[3] === value3) {
  10539. return;
  10540. }
  10541. this._blendFunctionParameters[0] = value0;
  10542. this._blendFunctionParameters[1] = value1;
  10543. this._blendFunctionParameters[2] = value2;
  10544. this._blendFunctionParameters[3] = value3;
  10545. this._isBlendFunctionParametersDirty = true;
  10546. };
  10547. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10548. if (this._blendEquationParameters[0] === rgb &&
  10549. this._blendEquationParameters[1] === alpha) {
  10550. return;
  10551. }
  10552. this._blendEquationParameters[0] = rgb;
  10553. this._blendEquationParameters[1] = alpha;
  10554. this._isBlendEquationParametersDirty = true;
  10555. };
  10556. _AlphaState.prototype.reset = function () {
  10557. this._alphaBlend = false;
  10558. this._blendFunctionParameters[0] = null;
  10559. this._blendFunctionParameters[1] = null;
  10560. this._blendFunctionParameters[2] = null;
  10561. this._blendFunctionParameters[3] = null;
  10562. this._blendEquationParameters[0] = null;
  10563. this._blendEquationParameters[1] = null;
  10564. this._blendConstants[0] = null;
  10565. this._blendConstants[1] = null;
  10566. this._blendConstants[2] = null;
  10567. this._blendConstants[3] = null;
  10568. this._isAlphaBlendDirty = true;
  10569. this._isBlendFunctionParametersDirty = false;
  10570. this._isBlendEquationParametersDirty = false;
  10571. this._isBlendConstantsDirty = false;
  10572. };
  10573. _AlphaState.prototype.apply = function (gl) {
  10574. if (!this.isDirty) {
  10575. return;
  10576. }
  10577. // Alpha blend
  10578. if (this._isAlphaBlendDirty) {
  10579. if (this._alphaBlend) {
  10580. gl.enable(gl.BLEND);
  10581. }
  10582. else {
  10583. gl.disable(gl.BLEND);
  10584. }
  10585. this._isAlphaBlendDirty = false;
  10586. }
  10587. // Alpha function
  10588. if (this._isBlendFunctionParametersDirty) {
  10589. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10590. this._isBlendFunctionParametersDirty = false;
  10591. }
  10592. // Alpha equation
  10593. if (this._isBlendEquationParametersDirty) {
  10594. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10595. this._isBlendEquationParametersDirty = false;
  10596. }
  10597. // Constants
  10598. if (this._isBlendConstantsDirty) {
  10599. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10600. this._isBlendConstantsDirty = false;
  10601. }
  10602. };
  10603. return _AlphaState;
  10604. }());
  10605. BABYLON._AlphaState = _AlphaState;
  10606. })(BABYLON || (BABYLON = {}));
  10607. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10608. var BABYLON;
  10609. (function (BABYLON) {
  10610. /**
  10611. * @hidden
  10612. **/
  10613. var _DepthCullingState = /** @class */ (function () {
  10614. /**
  10615. * Initializes the state.
  10616. */
  10617. function _DepthCullingState() {
  10618. this._isDepthTestDirty = false;
  10619. this._isDepthMaskDirty = false;
  10620. this._isDepthFuncDirty = false;
  10621. this._isCullFaceDirty = false;
  10622. this._isCullDirty = false;
  10623. this._isZOffsetDirty = false;
  10624. this._isFrontFaceDirty = false;
  10625. this.reset();
  10626. }
  10627. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10628. get: function () {
  10629. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10630. },
  10631. enumerable: true,
  10632. configurable: true
  10633. });
  10634. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10635. get: function () {
  10636. return this._zOffset;
  10637. },
  10638. set: function (value) {
  10639. if (this._zOffset === value) {
  10640. return;
  10641. }
  10642. this._zOffset = value;
  10643. this._isZOffsetDirty = true;
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10649. get: function () {
  10650. return this._cullFace;
  10651. },
  10652. set: function (value) {
  10653. if (this._cullFace === value) {
  10654. return;
  10655. }
  10656. this._cullFace = value;
  10657. this._isCullFaceDirty = true;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10663. get: function () {
  10664. return this._cull;
  10665. },
  10666. set: function (value) {
  10667. if (this._cull === value) {
  10668. return;
  10669. }
  10670. this._cull = value;
  10671. this._isCullDirty = true;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10677. get: function () {
  10678. return this._depthFunc;
  10679. },
  10680. set: function (value) {
  10681. if (this._depthFunc === value) {
  10682. return;
  10683. }
  10684. this._depthFunc = value;
  10685. this._isDepthFuncDirty = true;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10691. get: function () {
  10692. return this._depthMask;
  10693. },
  10694. set: function (value) {
  10695. if (this._depthMask === value) {
  10696. return;
  10697. }
  10698. this._depthMask = value;
  10699. this._isDepthMaskDirty = true;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10705. get: function () {
  10706. return this._depthTest;
  10707. },
  10708. set: function (value) {
  10709. if (this._depthTest === value) {
  10710. return;
  10711. }
  10712. this._depthTest = value;
  10713. this._isDepthTestDirty = true;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10719. get: function () {
  10720. return this._frontFace;
  10721. },
  10722. set: function (value) {
  10723. if (this._frontFace === value) {
  10724. return;
  10725. }
  10726. this._frontFace = value;
  10727. this._isFrontFaceDirty = true;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. _DepthCullingState.prototype.reset = function () {
  10733. this._depthMask = true;
  10734. this._depthTest = true;
  10735. this._depthFunc = null;
  10736. this._cullFace = null;
  10737. this._cull = null;
  10738. this._zOffset = 0;
  10739. this._frontFace = null;
  10740. this._isDepthTestDirty = true;
  10741. this._isDepthMaskDirty = true;
  10742. this._isDepthFuncDirty = false;
  10743. this._isCullFaceDirty = false;
  10744. this._isCullDirty = false;
  10745. this._isZOffsetDirty = false;
  10746. this._isFrontFaceDirty = false;
  10747. };
  10748. _DepthCullingState.prototype.apply = function (gl) {
  10749. if (!this.isDirty) {
  10750. return;
  10751. }
  10752. // Cull
  10753. if (this._isCullDirty) {
  10754. if (this.cull) {
  10755. gl.enable(gl.CULL_FACE);
  10756. }
  10757. else {
  10758. gl.disable(gl.CULL_FACE);
  10759. }
  10760. this._isCullDirty = false;
  10761. }
  10762. // Cull face
  10763. if (this._isCullFaceDirty) {
  10764. gl.cullFace(this.cullFace);
  10765. this._isCullFaceDirty = false;
  10766. }
  10767. // Depth mask
  10768. if (this._isDepthMaskDirty) {
  10769. gl.depthMask(this.depthMask);
  10770. this._isDepthMaskDirty = false;
  10771. }
  10772. // Depth test
  10773. if (this._isDepthTestDirty) {
  10774. if (this.depthTest) {
  10775. gl.enable(gl.DEPTH_TEST);
  10776. }
  10777. else {
  10778. gl.disable(gl.DEPTH_TEST);
  10779. }
  10780. this._isDepthTestDirty = false;
  10781. }
  10782. // Depth func
  10783. if (this._isDepthFuncDirty) {
  10784. gl.depthFunc(this.depthFunc);
  10785. this._isDepthFuncDirty = false;
  10786. }
  10787. // zOffset
  10788. if (this._isZOffsetDirty) {
  10789. if (this.zOffset) {
  10790. gl.enable(gl.POLYGON_OFFSET_FILL);
  10791. gl.polygonOffset(this.zOffset, 0);
  10792. }
  10793. else {
  10794. gl.disable(gl.POLYGON_OFFSET_FILL);
  10795. }
  10796. this._isZOffsetDirty = false;
  10797. }
  10798. // Front face
  10799. if (this._isFrontFaceDirty) {
  10800. gl.frontFace(this.frontFace);
  10801. this._isFrontFaceDirty = false;
  10802. }
  10803. };
  10804. return _DepthCullingState;
  10805. }());
  10806. BABYLON._DepthCullingState = _DepthCullingState;
  10807. })(BABYLON || (BABYLON = {}));
  10808. //# sourceMappingURL=babylon.depthCullingState.js.map
  10809. var BABYLON;
  10810. (function (BABYLON) {
  10811. /**
  10812. * @hidden
  10813. **/
  10814. var _StencilState = /** @class */ (function () {
  10815. function _StencilState() {
  10816. this._isStencilTestDirty = false;
  10817. this._isStencilMaskDirty = false;
  10818. this._isStencilFuncDirty = false;
  10819. this._isStencilOpDirty = false;
  10820. this.reset();
  10821. }
  10822. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10823. get: function () {
  10824. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10830. get: function () {
  10831. return this._stencilFunc;
  10832. },
  10833. set: function (value) {
  10834. if (this._stencilFunc === value) {
  10835. return;
  10836. }
  10837. this._stencilFunc = value;
  10838. this._isStencilFuncDirty = true;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10844. get: function () {
  10845. return this._stencilFuncRef;
  10846. },
  10847. set: function (value) {
  10848. if (this._stencilFuncRef === value) {
  10849. return;
  10850. }
  10851. this._stencilFuncRef = value;
  10852. this._isStencilFuncDirty = true;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10858. get: function () {
  10859. return this._stencilFuncMask;
  10860. },
  10861. set: function (value) {
  10862. if (this._stencilFuncMask === value) {
  10863. return;
  10864. }
  10865. this._stencilFuncMask = value;
  10866. this._isStencilFuncDirty = true;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10872. get: function () {
  10873. return this._stencilOpStencilFail;
  10874. },
  10875. set: function (value) {
  10876. if (this._stencilOpStencilFail === value) {
  10877. return;
  10878. }
  10879. this._stencilOpStencilFail = value;
  10880. this._isStencilOpDirty = true;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10886. get: function () {
  10887. return this._stencilOpDepthFail;
  10888. },
  10889. set: function (value) {
  10890. if (this._stencilOpDepthFail === value) {
  10891. return;
  10892. }
  10893. this._stencilOpDepthFail = value;
  10894. this._isStencilOpDirty = true;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10900. get: function () {
  10901. return this._stencilOpStencilDepthPass;
  10902. },
  10903. set: function (value) {
  10904. if (this._stencilOpStencilDepthPass === value) {
  10905. return;
  10906. }
  10907. this._stencilOpStencilDepthPass = value;
  10908. this._isStencilOpDirty = true;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10914. get: function () {
  10915. return this._stencilMask;
  10916. },
  10917. set: function (value) {
  10918. if (this._stencilMask === value) {
  10919. return;
  10920. }
  10921. this._stencilMask = value;
  10922. this._isStencilMaskDirty = true;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10928. get: function () {
  10929. return this._stencilTest;
  10930. },
  10931. set: function (value) {
  10932. if (this._stencilTest === value) {
  10933. return;
  10934. }
  10935. this._stencilTest = value;
  10936. this._isStencilTestDirty = true;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. _StencilState.prototype.reset = function () {
  10942. this._stencilTest = false;
  10943. this._stencilMask = 0xFF;
  10944. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10945. this._stencilFuncRef = 1;
  10946. this._stencilFuncMask = 0xFF;
  10947. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10948. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10949. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10950. this._isStencilTestDirty = true;
  10951. this._isStencilMaskDirty = true;
  10952. this._isStencilFuncDirty = true;
  10953. this._isStencilOpDirty = true;
  10954. };
  10955. _StencilState.prototype.apply = function (gl) {
  10956. if (!this.isDirty) {
  10957. return;
  10958. }
  10959. // Stencil test
  10960. if (this._isStencilTestDirty) {
  10961. if (this.stencilTest) {
  10962. gl.enable(gl.STENCIL_TEST);
  10963. }
  10964. else {
  10965. gl.disable(gl.STENCIL_TEST);
  10966. }
  10967. this._isStencilTestDirty = false;
  10968. }
  10969. // Stencil mask
  10970. if (this._isStencilMaskDirty) {
  10971. gl.stencilMask(this.stencilMask);
  10972. this._isStencilMaskDirty = false;
  10973. }
  10974. // Stencil func
  10975. if (this._isStencilFuncDirty) {
  10976. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10977. this._isStencilFuncDirty = false;
  10978. }
  10979. // Stencil op
  10980. if (this._isStencilOpDirty) {
  10981. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10982. this._isStencilOpDirty = false;
  10983. }
  10984. };
  10985. return _StencilState;
  10986. }());
  10987. BABYLON._StencilState = _StencilState;
  10988. })(BABYLON || (BABYLON = {}));
  10989. //# sourceMappingURL=babylon.stencilState.js.map
  10990. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10991. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10992. s = arguments[i];
  10993. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10994. t[p] = s[p];
  10995. }
  10996. return t;
  10997. };
  10998. var BABYLON;
  10999. (function (BABYLON) {
  11000. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11001. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11002. };
  11003. var compileRawShader = function (gl, source, type) {
  11004. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11005. gl.shaderSource(shader, source);
  11006. gl.compileShader(shader);
  11007. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11008. var log = gl.getShaderInfoLog(shader);
  11009. if (log) {
  11010. throw new Error(log);
  11011. }
  11012. }
  11013. if (!shader) {
  11014. throw new Error("Something went wrong while compile the shader.");
  11015. }
  11016. return shader;
  11017. };
  11018. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11019. var magFilter = gl.NEAREST;
  11020. var minFilter = gl.NEAREST;
  11021. switch (samplingMode) {
  11022. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11023. magFilter = gl.LINEAR;
  11024. if (generateMipMaps) {
  11025. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11026. }
  11027. else {
  11028. minFilter = gl.LINEAR;
  11029. }
  11030. break;
  11031. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11032. magFilter = gl.LINEAR;
  11033. if (generateMipMaps) {
  11034. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11035. }
  11036. else {
  11037. minFilter = gl.LINEAR;
  11038. }
  11039. break;
  11040. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11041. magFilter = gl.NEAREST;
  11042. if (generateMipMaps) {
  11043. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11044. }
  11045. else {
  11046. minFilter = gl.NEAREST;
  11047. }
  11048. break;
  11049. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11050. magFilter = gl.NEAREST;
  11051. if (generateMipMaps) {
  11052. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11053. }
  11054. else {
  11055. minFilter = gl.NEAREST;
  11056. }
  11057. break;
  11058. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11059. magFilter = gl.NEAREST;
  11060. if (generateMipMaps) {
  11061. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11062. }
  11063. else {
  11064. minFilter = gl.LINEAR;
  11065. }
  11066. break;
  11067. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11068. magFilter = gl.NEAREST;
  11069. if (generateMipMaps) {
  11070. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11071. }
  11072. else {
  11073. minFilter = gl.LINEAR;
  11074. }
  11075. break;
  11076. case BABYLON.Texture.NEAREST_LINEAR:
  11077. magFilter = gl.NEAREST;
  11078. minFilter = gl.LINEAR;
  11079. break;
  11080. case BABYLON.Texture.NEAREST_NEAREST:
  11081. magFilter = gl.NEAREST;
  11082. minFilter = gl.NEAREST;
  11083. break;
  11084. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11085. magFilter = gl.LINEAR;
  11086. if (generateMipMaps) {
  11087. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11088. }
  11089. else {
  11090. minFilter = gl.NEAREST;
  11091. }
  11092. break;
  11093. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11094. magFilter = gl.LINEAR;
  11095. if (generateMipMaps) {
  11096. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11097. }
  11098. else {
  11099. minFilter = gl.NEAREST;
  11100. }
  11101. break;
  11102. case BABYLON.Texture.LINEAR_LINEAR:
  11103. magFilter = gl.LINEAR;
  11104. minFilter = gl.LINEAR;
  11105. break;
  11106. case BABYLON.Texture.LINEAR_NEAREST:
  11107. magFilter = gl.LINEAR;
  11108. minFilter = gl.NEAREST;
  11109. break;
  11110. }
  11111. return {
  11112. min: minFilter,
  11113. mag: magFilter
  11114. };
  11115. };
  11116. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11117. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11118. var img;
  11119. var onload = function () {
  11120. loadedImages[index] = img;
  11121. loadedImages._internalCount++;
  11122. if (scene) {
  11123. scene._removePendingData(img);
  11124. }
  11125. if (loadedImages._internalCount === 6) {
  11126. onfinish(loadedImages);
  11127. }
  11128. };
  11129. var onerror = function (message, exception) {
  11130. if (scene) {
  11131. scene._removePendingData(img);
  11132. }
  11133. if (onErrorCallBack) {
  11134. onErrorCallBack(message, exception);
  11135. }
  11136. };
  11137. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11138. if (scene) {
  11139. scene._addPendingData(img);
  11140. }
  11141. };
  11142. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11143. if (onError === void 0) { onError = null; }
  11144. var loadedImages = [];
  11145. loadedImages._internalCount = 0;
  11146. for (var index = 0; index < 6; index++) {
  11147. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11148. }
  11149. };
  11150. var BufferPointer = /** @class */ (function () {
  11151. function BufferPointer() {
  11152. }
  11153. return BufferPointer;
  11154. }());
  11155. /**
  11156. * Interface for attribute information associated with buffer instanciation
  11157. */
  11158. var InstancingAttributeInfo = /** @class */ (function () {
  11159. function InstancingAttributeInfo() {
  11160. }
  11161. return InstancingAttributeInfo;
  11162. }());
  11163. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11164. /**
  11165. * Define options used to create a render target texture
  11166. */
  11167. var RenderTargetCreationOptions = /** @class */ (function () {
  11168. function RenderTargetCreationOptions() {
  11169. }
  11170. return RenderTargetCreationOptions;
  11171. }());
  11172. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11173. /**
  11174. * Define options used to create a depth texture
  11175. */
  11176. var DepthTextureCreationOptions = /** @class */ (function () {
  11177. function DepthTextureCreationOptions() {
  11178. }
  11179. return DepthTextureCreationOptions;
  11180. }());
  11181. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11182. /**
  11183. * Class used to describe the capabilities of the engine relatively to the current browser
  11184. */
  11185. var EngineCapabilities = /** @class */ (function () {
  11186. function EngineCapabilities() {
  11187. }
  11188. return EngineCapabilities;
  11189. }());
  11190. BABYLON.EngineCapabilities = EngineCapabilities;
  11191. /**
  11192. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11193. */
  11194. var Engine = /** @class */ (function () {
  11195. /**
  11196. * Creates a new engine
  11197. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11198. * @param antialias defines enable antialiasing (default: false)
  11199. * @param options defines further options to be sent to the getContext() function
  11200. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11201. */
  11202. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11203. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11204. var _this = this;
  11205. // Public members
  11206. /**
  11207. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11208. */
  11209. this.forcePOTTextures = false;
  11210. /**
  11211. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11212. */
  11213. this.isFullscreen = false;
  11214. /**
  11215. * Gets a boolean indicating if the pointer is currently locked
  11216. */
  11217. this.isPointerLock = false;
  11218. /**
  11219. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11220. */
  11221. this.cullBackFaces = true;
  11222. /**
  11223. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11224. */
  11225. this.renderEvenInBackground = true;
  11226. /**
  11227. * Gets or sets a boolean indicating that cache can be kept between frames
  11228. */
  11229. this.preventCacheWipeBetweenFrames = false;
  11230. /**
  11231. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11232. **/
  11233. this.enableOfflineSupport = false;
  11234. /**
  11235. * 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)
  11236. **/
  11237. this.disableManifestCheck = false;
  11238. /**
  11239. * Gets the list of created scenes
  11240. */
  11241. this.scenes = new Array();
  11242. /**
  11243. * Gets the list of created postprocesses
  11244. */
  11245. this.postProcesses = new Array();
  11246. // Observables
  11247. /**
  11248. * Observable event triggered each time the rendering canvas is resized
  11249. */
  11250. this.onResizeObservable = new BABYLON.Observable();
  11251. /**
  11252. * Observable event triggered each time the canvas loses focus
  11253. */
  11254. this.onCanvasBlurObservable = new BABYLON.Observable();
  11255. /**
  11256. * Observable event triggered each time the canvas gains focus
  11257. */
  11258. this.onCanvasFocusObservable = new BABYLON.Observable();
  11259. /**
  11260. * Observable event triggered each time the canvas receives pointerout event
  11261. */
  11262. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11263. /**
  11264. * Observable event triggered before each texture is initialized
  11265. */
  11266. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11267. //WebVR
  11268. this._vrDisplay = undefined;
  11269. this._vrSupported = false;
  11270. this._vrExclusivePointerMode = false;
  11271. // Uniform buffers list
  11272. /**
  11273. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11274. */
  11275. this.disableUniformBuffers = false;
  11276. /** @hidden */
  11277. this._uniformBuffers = new Array();
  11278. // Observables
  11279. /**
  11280. * Observable raised when the engine begins a new frame
  11281. */
  11282. this.onBeginFrameObservable = new BABYLON.Observable();
  11283. /**
  11284. * Observable raised when the engine ends the current frame
  11285. */
  11286. this.onEndFrameObservable = new BABYLON.Observable();
  11287. /**
  11288. * Observable raised when the engine is about to compile a shader
  11289. */
  11290. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11291. /**
  11292. * Observable raised when the engine has jsut compiled a shader
  11293. */
  11294. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11295. this._windowIsBackground = false;
  11296. this._webGLVersion = 1.0;
  11297. /** @hidden */
  11298. this._badOS = false;
  11299. /** @hidden */
  11300. this._badDesktopOS = false;
  11301. /**
  11302. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11303. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11304. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11305. */
  11306. this.disableTextureBindingOptimization = false;
  11307. /**
  11308. * Observable signaled when VR display mode changes
  11309. */
  11310. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11311. /**
  11312. * Observable signaled when VR request present is complete
  11313. */
  11314. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11315. /**
  11316. * Observable signaled when VR request present starts
  11317. */
  11318. this.onVRRequestPresentStart = new BABYLON.Observable();
  11319. this._colorWrite = true;
  11320. /** @hidden */
  11321. this._drawCalls = new BABYLON.PerfCounter();
  11322. /** @hidden */
  11323. this._textureCollisions = new BABYLON.PerfCounter();
  11324. this._renderingQueueLaunched = false;
  11325. this._activeRenderLoops = new Array();
  11326. // Deterministic lockstepMaxSteps
  11327. this._deterministicLockstep = false;
  11328. this._lockstepMaxSteps = 4;
  11329. // Lost context
  11330. /**
  11331. * Observable signaled when a context lost event is raised
  11332. */
  11333. this.onContextLostObservable = new BABYLON.Observable();
  11334. /**
  11335. * Observable signaled when a context restored event is raised
  11336. */
  11337. this.onContextRestoredObservable = new BABYLON.Observable();
  11338. this._contextWasLost = false;
  11339. this._doNotHandleContextLost = false;
  11340. // FPS
  11341. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11342. this._fps = 60;
  11343. this._deltaTime = 0;
  11344. /**
  11345. * Turn this value on if you want to pause FPS computation when in background
  11346. */
  11347. this.disablePerformanceMonitorInBackground = false;
  11348. // States
  11349. /** @hidden */
  11350. this._depthCullingState = new BABYLON._DepthCullingState();
  11351. /** @hidden */
  11352. this._stencilState = new BABYLON._StencilState();
  11353. /** @hidden */
  11354. this._alphaState = new BABYLON._AlphaState();
  11355. /** @hidden */
  11356. this._alphaMode = Engine.ALPHA_DISABLE;
  11357. // Cache
  11358. this._internalTexturesCache = new Array();
  11359. /** @hidden */
  11360. this._activeChannel = 0;
  11361. this._currentTextureChannel = -1;
  11362. /** @hidden */
  11363. this._boundTexturesCache = {};
  11364. this._compiledEffects = {};
  11365. this._vertexAttribArraysEnabled = [];
  11366. this._uintIndicesCurrentlySet = false;
  11367. this._currentBoundBuffer = new Array();
  11368. this._currentBufferPointers = new Array();
  11369. this._currentInstanceLocations = new Array();
  11370. this._currentInstanceBuffers = new Array();
  11371. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11372. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11373. this._vaoRecordInProgress = false;
  11374. this._mustWipeVertexAttributes = false;
  11375. this._nextFreeTextureSlots = new Array();
  11376. this._maxSimultaneousTextures = 0;
  11377. this._activeRequests = new Array();
  11378. // Hardware supported Compressed Textures
  11379. this._texturesSupported = new Array();
  11380. /**
  11381. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11382. */
  11383. this.premultipliedAlpha = true;
  11384. this._onVRFullScreenTriggered = function () {
  11385. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11386. //get the old size before we change
  11387. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11388. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11389. //get the width and height, change the render size
  11390. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11391. _this.setHardwareScalingLevel(1);
  11392. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11393. }
  11394. else {
  11395. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11396. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11397. }
  11398. };
  11399. this._boundUniforms = {};
  11400. // Register promises
  11401. BABYLON.PromisePolyfill.Apply();
  11402. var canvas = null;
  11403. Engine.Instances.push(this);
  11404. if (!canvasOrContext) {
  11405. return;
  11406. }
  11407. options = options || {};
  11408. if (canvasOrContext.getContext) {
  11409. canvas = canvasOrContext;
  11410. this._renderingCanvas = canvas;
  11411. if (antialias != null) {
  11412. options.antialias = antialias;
  11413. }
  11414. if (options.deterministicLockstep === undefined) {
  11415. options.deterministicLockstep = false;
  11416. }
  11417. if (options.lockstepMaxSteps === undefined) {
  11418. options.lockstepMaxSteps = 4;
  11419. }
  11420. if (options.preserveDrawingBuffer === undefined) {
  11421. options.preserveDrawingBuffer = false;
  11422. }
  11423. if (options.audioEngine === undefined) {
  11424. options.audioEngine = true;
  11425. }
  11426. if (options.stencil === undefined) {
  11427. options.stencil = true;
  11428. }
  11429. if (options.premultipliedAlpha === false) {
  11430. this.premultipliedAlpha = false;
  11431. }
  11432. this._deterministicLockstep = options.deterministicLockstep;
  11433. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11434. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11435. // Exceptions
  11436. if (navigator && navigator.userAgent) {
  11437. var ua = navigator.userAgent;
  11438. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11439. var exception = _a[_i];
  11440. var key = exception.key;
  11441. var targets = exception.targets;
  11442. if (ua.indexOf(key) > -1) {
  11443. if (exception.capture && exception.captureConstraint) {
  11444. var capture = exception.capture;
  11445. var constraint = exception.captureConstraint;
  11446. var regex = new RegExp(capture);
  11447. var matches = regex.exec(ua);
  11448. if (matches && matches.length > 0) {
  11449. var capturedValue = parseInt(matches[matches.length - 1]);
  11450. if (capturedValue >= constraint) {
  11451. continue;
  11452. }
  11453. }
  11454. }
  11455. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11456. var target = targets_1[_b];
  11457. switch (target) {
  11458. case "uniformBuffer":
  11459. this.disableUniformBuffers = true;
  11460. break;
  11461. case "textureBindingOptimization":
  11462. this.disableTextureBindingOptimization = true;
  11463. break;
  11464. }
  11465. }
  11466. }
  11467. }
  11468. }
  11469. // GL
  11470. if (!options.disableWebGL2Support) {
  11471. try {
  11472. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11473. if (this._gl) {
  11474. this._webGLVersion = 2.0;
  11475. }
  11476. }
  11477. catch (e) {
  11478. // Do nothing
  11479. }
  11480. }
  11481. if (!this._gl) {
  11482. if (!canvas) {
  11483. throw new Error("The provided canvas is null or undefined.");
  11484. }
  11485. try {
  11486. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11487. }
  11488. catch (e) {
  11489. throw new Error("WebGL not supported");
  11490. }
  11491. }
  11492. if (!this._gl) {
  11493. throw new Error("WebGL not supported");
  11494. }
  11495. this._onCanvasFocus = function () {
  11496. _this.onCanvasFocusObservable.notifyObservers(_this);
  11497. };
  11498. this._onCanvasBlur = function () {
  11499. _this.onCanvasBlurObservable.notifyObservers(_this);
  11500. };
  11501. canvas.addEventListener("focus", this._onCanvasFocus);
  11502. canvas.addEventListener("blur", this._onCanvasBlur);
  11503. this._onBlur = function () {
  11504. if (_this.disablePerformanceMonitorInBackground) {
  11505. _this._performanceMonitor.disable();
  11506. }
  11507. _this._windowIsBackground = true;
  11508. };
  11509. this._onFocus = function () {
  11510. if (_this.disablePerformanceMonitorInBackground) {
  11511. _this._performanceMonitor.enable();
  11512. }
  11513. _this._windowIsBackground = false;
  11514. };
  11515. this._onCanvasPointerOut = function (ev) {
  11516. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11517. };
  11518. window.addEventListener("blur", this._onBlur);
  11519. window.addEventListener("focus", this._onFocus);
  11520. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11521. // Context lost
  11522. if (!this._doNotHandleContextLost) {
  11523. this._onContextLost = function (evt) {
  11524. evt.preventDefault();
  11525. _this._contextWasLost = true;
  11526. BABYLON.Tools.Warn("WebGL context lost.");
  11527. _this.onContextLostObservable.notifyObservers(_this);
  11528. };
  11529. this._onContextRestored = function (evt) {
  11530. // Adding a timeout to avoid race condition at browser level
  11531. setTimeout(function () {
  11532. // Rebuild gl context
  11533. _this._initGLContext();
  11534. // Rebuild effects
  11535. _this._rebuildEffects();
  11536. // Rebuild textures
  11537. _this._rebuildInternalTextures();
  11538. // Rebuild buffers
  11539. _this._rebuildBuffers();
  11540. // Cache
  11541. _this.wipeCaches(true);
  11542. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11543. _this.onContextRestoredObservable.notifyObservers(_this);
  11544. _this._contextWasLost = false;
  11545. }, 0);
  11546. };
  11547. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11548. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11549. }
  11550. }
  11551. else {
  11552. this._gl = canvasOrContext;
  11553. this._renderingCanvas = this._gl.canvas;
  11554. if (this._gl.renderbufferStorageMultisample) {
  11555. this._webGLVersion = 2.0;
  11556. }
  11557. options.stencil = this._gl.getContextAttributes().stencil;
  11558. }
  11559. // Viewport
  11560. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11561. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11562. this.resize();
  11563. this._isStencilEnable = options.stencil ? true : false;
  11564. this._initGLContext();
  11565. if (canvas) {
  11566. // Fullscreen
  11567. this._onFullscreenChange = function () {
  11568. if (document.fullscreen !== undefined) {
  11569. _this.isFullscreen = document.fullscreen;
  11570. }
  11571. else if (document.mozFullScreen !== undefined) {
  11572. _this.isFullscreen = document.mozFullScreen;
  11573. }
  11574. else if (document.webkitIsFullScreen !== undefined) {
  11575. _this.isFullscreen = document.webkitIsFullScreen;
  11576. }
  11577. else if (document.msIsFullScreen !== undefined) {
  11578. _this.isFullscreen = document.msIsFullScreen;
  11579. }
  11580. // Pointer lock
  11581. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11582. canvas.requestPointerLock = canvas.requestPointerLock ||
  11583. canvas.msRequestPointerLock ||
  11584. canvas.mozRequestPointerLock ||
  11585. canvas.webkitRequestPointerLock;
  11586. if (canvas.requestPointerLock) {
  11587. canvas.requestPointerLock();
  11588. }
  11589. }
  11590. };
  11591. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11592. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11593. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11594. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11595. // Pointer lock
  11596. this._onPointerLockChange = function () {
  11597. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11598. document.webkitPointerLockElement === canvas ||
  11599. document.msPointerLockElement === canvas ||
  11600. document.pointerLockElement === canvas);
  11601. };
  11602. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11603. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11604. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11605. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11606. this._onVRDisplayPointerRestricted = function () {
  11607. if (canvas) {
  11608. canvas.requestPointerLock();
  11609. }
  11610. };
  11611. this._onVRDisplayPointerUnrestricted = function () {
  11612. document.exitPointerLock();
  11613. };
  11614. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11615. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11616. }
  11617. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11618. Engine.audioEngine = new BABYLON.AudioEngine();
  11619. }
  11620. // Prepare buffer pointers
  11621. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11622. this._currentBufferPointers[i] = new BufferPointer();
  11623. }
  11624. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11625. // Load WebVR Devices
  11626. if (options.autoEnableWebVR) {
  11627. this.initWebVR();
  11628. }
  11629. // Detect if we are running on a faulty buggy OS.
  11630. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11631. // Detect if we are running on a faulty buggy desktop OS.
  11632. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11633. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11634. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11635. }
  11636. Object.defineProperty(Engine, "LastCreatedEngine", {
  11637. /**
  11638. * Gets the latest created engine
  11639. */
  11640. get: function () {
  11641. if (Engine.Instances.length === 0) {
  11642. return null;
  11643. }
  11644. return Engine.Instances[Engine.Instances.length - 1];
  11645. },
  11646. enumerable: true,
  11647. configurable: true
  11648. });
  11649. Object.defineProperty(Engine, "LastCreatedScene", {
  11650. /**
  11651. * Gets the latest created scene
  11652. */
  11653. get: function () {
  11654. var lastCreatedEngine = Engine.LastCreatedEngine;
  11655. if (!lastCreatedEngine) {
  11656. return null;
  11657. }
  11658. if (lastCreatedEngine.scenes.length === 0) {
  11659. return null;
  11660. }
  11661. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. /**
  11667. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11668. * @param flag defines which part of the materials must be marked as dirty
  11669. * @param predicate defines a predicate used to filter which materials should be affected
  11670. */
  11671. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11672. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11673. var engine = Engine.Instances[engineIndex];
  11674. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11675. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11676. }
  11677. }
  11678. };
  11679. Object.defineProperty(Engine, "NEVER", {
  11680. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11681. get: function () {
  11682. return Engine._NEVER;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Object.defineProperty(Engine, "ALWAYS", {
  11688. /** 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 */
  11689. get: function () {
  11690. return Engine._ALWAYS;
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Engine, "LESS", {
  11696. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11697. get: function () {
  11698. return Engine._LESS;
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. Object.defineProperty(Engine, "EQUAL", {
  11704. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11705. get: function () {
  11706. return Engine._EQUAL;
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(Engine, "LEQUAL", {
  11712. /** 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 */
  11713. get: function () {
  11714. return Engine._LEQUAL;
  11715. },
  11716. enumerable: true,
  11717. configurable: true
  11718. });
  11719. Object.defineProperty(Engine, "GREATER", {
  11720. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11721. get: function () {
  11722. return Engine._GREATER;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(Engine, "GEQUAL", {
  11728. /** 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 */
  11729. get: function () {
  11730. return Engine._GEQUAL;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Engine, "NOTEQUAL", {
  11736. /** 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 */
  11737. get: function () {
  11738. return Engine._NOTEQUAL;
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. Object.defineProperty(Engine, "KEEP", {
  11744. /** Passed to stencilOperation to specify that stencil value must be kept */
  11745. get: function () {
  11746. return Engine._KEEP;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Object.defineProperty(Engine, "REPLACE", {
  11752. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11753. get: function () {
  11754. return Engine._REPLACE;
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. Object.defineProperty(Engine, "INCR", {
  11760. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11761. get: function () {
  11762. return Engine._INCR;
  11763. },
  11764. enumerable: true,
  11765. configurable: true
  11766. });
  11767. Object.defineProperty(Engine, "DECR", {
  11768. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11769. get: function () {
  11770. return Engine._DECR;
  11771. },
  11772. enumerable: true,
  11773. configurable: true
  11774. });
  11775. Object.defineProperty(Engine, "INVERT", {
  11776. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11777. get: function () {
  11778. return Engine._INVERT;
  11779. },
  11780. enumerable: true,
  11781. configurable: true
  11782. });
  11783. Object.defineProperty(Engine, "INCR_WRAP", {
  11784. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11785. get: function () {
  11786. return Engine._INCR_WRAP;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine, "DECR_WRAP", {
  11792. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11793. get: function () {
  11794. return Engine._DECR_WRAP;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11800. // Alpha
  11801. /** Defines that alpha blending is disabled */
  11802. get: function () {
  11803. return Engine._ALPHA_DISABLE;
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11809. /** Defines that alpha blending to SRC + DEST */
  11810. get: function () {
  11811. return Engine._ALPHA_ONEONE;
  11812. },
  11813. enumerable: true,
  11814. configurable: true
  11815. });
  11816. Object.defineProperty(Engine, "ALPHA_ADD", {
  11817. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11818. get: function () {
  11819. return Engine._ALPHA_ADD;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11825. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11826. get: function () {
  11827. return Engine._ALPHA_COMBINE;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11833. /** Defines that alpha blending to DEST - SRC * DEST */
  11834. get: function () {
  11835. return Engine._ALPHA_SUBTRACT;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11841. /** Defines that alpha blending to SRC * DEST */
  11842. get: function () {
  11843. return Engine._ALPHA_MULTIPLY;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11849. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11850. get: function () {
  11851. return Engine._ALPHA_MAXIMIZED;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11857. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11858. get: function () {
  11859. return Engine._ALPHA_PREMULTIPLIED;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11865. /**
  11866. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11867. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11868. */
  11869. get: function () {
  11870. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11876. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11877. get: function () {
  11878. return Engine._ALPHA_INTERPOLATE;
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11884. /**
  11885. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11886. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11887. */
  11888. get: function () {
  11889. return Engine._ALPHA_SCREENMODE;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11895. // Delays
  11896. /** Defines that the ressource is not delayed*/
  11897. get: function () {
  11898. return Engine._DELAYLOADSTATE_NONE;
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11904. /** Defines that the ressource was successfully delay loaded */
  11905. get: function () {
  11906. return Engine._DELAYLOADSTATE_LOADED;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11912. /** Defines that the ressource is currently delay loading */
  11913. get: function () {
  11914. return Engine._DELAYLOADSTATE_LOADING;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11920. /** Defines that the ressource is delayed and has not started loading */
  11921. get: function () {
  11922. return Engine._DELAYLOADSTATE_NOTLOADED;
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11928. /** ALPHA */
  11929. get: function () {
  11930. return Engine._TEXTUREFORMAT_ALPHA;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11936. /** LUMINANCE */
  11937. get: function () {
  11938. return Engine._TEXTUREFORMAT_LUMINANCE;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11944. /**
  11945. * R
  11946. */
  11947. get: function () {
  11948. return Engine._TEXTUREFORMAT_R;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11954. /**
  11955. * RG
  11956. */
  11957. get: function () {
  11958. return Engine._TEXTUREFORMAT_RG;
  11959. },
  11960. enumerable: true,
  11961. configurable: true
  11962. });
  11963. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11964. /** LUMINANCE_ALPHA */
  11965. get: function () {
  11966. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11972. /** RGB */
  11973. get: function () {
  11974. return Engine._TEXTUREFORMAT_RGB;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11980. /** RGBA */
  11981. get: function () {
  11982. return Engine._TEXTUREFORMAT_RGBA;
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11988. /** UNSIGNED_INT */
  11989. get: function () {
  11990. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11996. /** FLOAT */
  11997. get: function () {
  11998. return Engine._TEXTURETYPE_FLOAT;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12004. /** HALF_FLOAT */
  12005. get: function () {
  12006. return Engine._TEXTURETYPE_HALF_FLOAT;
  12007. },
  12008. enumerable: true,
  12009. configurable: true
  12010. });
  12011. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12012. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12013. get: function () {
  12014. return Engine._SCALEMODE_FLOOR;
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12020. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12021. get: function () {
  12022. return Engine._SCALEMODE_NEAREST;
  12023. },
  12024. enumerable: true,
  12025. configurable: true
  12026. });
  12027. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12028. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12029. get: function () {
  12030. return Engine._SCALEMODE_CEILING;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Engine, "Version", {
  12036. /**
  12037. * Returns the current version of the framework
  12038. */
  12039. get: function () {
  12040. return "3.3.0-alpha.5";
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12046. /**
  12047. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12048. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12049. */
  12050. get: function () {
  12051. return this._vrExclusivePointerMode;
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12057. /**
  12058. * Gets a boolean indicating that the engine supports uniform buffers
  12059. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12060. */
  12061. get: function () {
  12062. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12063. },
  12064. enumerable: true,
  12065. configurable: true
  12066. });
  12067. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12068. /**
  12069. * Gets a boolean indicating that only power of 2 textures are supported
  12070. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12071. */
  12072. get: function () {
  12073. return this._webGLVersion < 2 || this.forcePOTTextures;
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12079. /**
  12080. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12081. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12082. */
  12083. get: function () {
  12084. return this._doNotHandleContextLost;
  12085. },
  12086. set: function (value) {
  12087. this._doNotHandleContextLost = value;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12093. /**
  12094. * Gets the performance monitor attached to this engine
  12095. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12096. */
  12097. get: function () {
  12098. return this._performanceMonitor;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12104. /**
  12105. * Gets the list of texture formats supported
  12106. */
  12107. get: function () {
  12108. return this._texturesSupported;
  12109. },
  12110. enumerable: true,
  12111. configurable: true
  12112. });
  12113. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12114. /**
  12115. * Gets the list of texture formats in use
  12116. */
  12117. get: function () {
  12118. return this._textureFormatInUse;
  12119. },
  12120. enumerable: true,
  12121. configurable: true
  12122. });
  12123. Object.defineProperty(Engine.prototype, "currentViewport", {
  12124. /**
  12125. * Gets the current viewport
  12126. */
  12127. get: function () {
  12128. return this._cachedViewport;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12134. /**
  12135. * Gets the default empty texture
  12136. */
  12137. get: function () {
  12138. if (!this._emptyTexture) {
  12139. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12140. }
  12141. return this._emptyTexture;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12147. /**
  12148. * Gets the default empty 3D texture
  12149. */
  12150. get: function () {
  12151. if (!this._emptyTexture3D) {
  12152. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12153. }
  12154. return this._emptyTexture3D;
  12155. },
  12156. enumerable: true,
  12157. configurable: true
  12158. });
  12159. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12160. /**
  12161. * Gets the default empty cube texture
  12162. */
  12163. get: function () {
  12164. if (!this._emptyCubeTexture) {
  12165. var faceData = new Uint8Array(4);
  12166. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12167. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12168. }
  12169. return this._emptyCubeTexture;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Engine.prototype._rebuildInternalTextures = function () {
  12175. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12176. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12177. var internalTexture = currentState_1[_i];
  12178. internalTexture._rebuild();
  12179. }
  12180. };
  12181. Engine.prototype._rebuildEffects = function () {
  12182. for (var key in this._compiledEffects) {
  12183. var effect = this._compiledEffects[key];
  12184. effect._prepareEffect();
  12185. }
  12186. BABYLON.Effect.ResetCache();
  12187. };
  12188. Engine.prototype._rebuildBuffers = function () {
  12189. // Index / Vertex
  12190. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12191. var scene = _a[_i];
  12192. scene.resetCachedMaterial();
  12193. scene._rebuildGeometries();
  12194. scene._rebuildTextures();
  12195. }
  12196. // Uniforms
  12197. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12198. var uniformBuffer = _c[_b];
  12199. uniformBuffer._rebuild();
  12200. }
  12201. };
  12202. Engine.prototype._initGLContext = function () {
  12203. // Caps
  12204. this._caps = new EngineCapabilities();
  12205. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12206. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12207. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12208. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12209. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12210. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12211. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12212. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12213. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12214. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12215. // Infos
  12216. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12217. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12218. if (rendererInfo != null) {
  12219. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12220. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12221. }
  12222. if (!this._glVendor) {
  12223. this._glVendor = "Unknown vendor";
  12224. }
  12225. if (!this._glRenderer) {
  12226. this._glRenderer = "Unknown renderer";
  12227. }
  12228. // Constants
  12229. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12230. if (this._gl.RGBA16F !== 0x881A) {
  12231. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12232. }
  12233. if (this._gl.RGBA32F !== 0x8814) {
  12234. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12235. }
  12236. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12237. this._gl.DEPTH24_STENCIL8 = 35056;
  12238. }
  12239. // Extensions
  12240. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12241. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12242. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12243. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12244. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12245. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12246. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12247. 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');
  12248. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12249. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12250. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12251. this._caps.highPrecisionShaderSupported = true;
  12252. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12253. if (this._caps.timerQuery) {
  12254. if (this._webGLVersion === 1) {
  12255. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12256. }
  12257. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12258. }
  12259. // Checks if some of the format renders first to allow the use of webgl inspector.
  12260. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12261. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12262. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12263. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12264. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12265. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12266. if (this._webGLVersion > 1) {
  12267. this._gl.HALF_FLOAT_OES = 0x140B;
  12268. }
  12269. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12270. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12271. // Draw buffers
  12272. if (this._webGLVersion > 1) {
  12273. this._caps.drawBuffersExtension = true;
  12274. }
  12275. else {
  12276. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12277. if (drawBuffersExtension !== null) {
  12278. this._caps.drawBuffersExtension = true;
  12279. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12280. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12281. for (var i = 0; i < 16; i++) {
  12282. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12283. }
  12284. }
  12285. else {
  12286. this._caps.drawBuffersExtension = false;
  12287. }
  12288. }
  12289. // Depth Texture
  12290. if (this._webGLVersion > 1) {
  12291. this._caps.depthTextureExtension = true;
  12292. }
  12293. else {
  12294. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12295. if (depthTextureExtension != null) {
  12296. this._caps.depthTextureExtension = true;
  12297. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12298. }
  12299. }
  12300. // Vertex array object
  12301. if (this._webGLVersion > 1) {
  12302. this._caps.vertexArrayObject = true;
  12303. }
  12304. else {
  12305. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12306. if (vertexArrayObjectExtension != null) {
  12307. this._caps.vertexArrayObject = true;
  12308. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12309. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12310. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12311. }
  12312. else {
  12313. this._caps.vertexArrayObject = false;
  12314. }
  12315. }
  12316. // Instances count
  12317. if (this._webGLVersion > 1) {
  12318. this._caps.instancedArrays = true;
  12319. }
  12320. else {
  12321. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12322. if (instanceExtension != null) {
  12323. this._caps.instancedArrays = true;
  12324. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12325. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12326. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12327. }
  12328. else {
  12329. this._caps.instancedArrays = false;
  12330. }
  12331. }
  12332. // Intelligently add supported compressed formats in order to check for.
  12333. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12334. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12335. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12336. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12337. if (this._caps.astc)
  12338. this.texturesSupported.push('-astc.ktx');
  12339. if (this._caps.s3tc)
  12340. this.texturesSupported.push('-dxt.ktx');
  12341. if (this._caps.pvrtc)
  12342. this.texturesSupported.push('-pvrtc.ktx');
  12343. if (this._caps.etc2)
  12344. this.texturesSupported.push('-etc2.ktx');
  12345. if (this._caps.etc1)
  12346. this.texturesSupported.push('-etc1.ktx');
  12347. if (this._gl.getShaderPrecisionFormat) {
  12348. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12349. if (highp) {
  12350. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12351. }
  12352. }
  12353. // Depth buffer
  12354. this.setDepthBuffer(true);
  12355. this.setDepthFunctionToLessOrEqual();
  12356. this.setDepthWrite(true);
  12357. // Texture maps
  12358. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12359. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12360. this._nextFreeTextureSlots.push(slot);
  12361. }
  12362. };
  12363. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12364. /**
  12365. * Gets version of the current webGL context
  12366. */
  12367. get: function () {
  12368. return this._webGLVersion;
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12374. /**
  12375. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12376. */
  12377. get: function () {
  12378. return this._isStencilEnable;
  12379. },
  12380. enumerable: true,
  12381. configurable: true
  12382. });
  12383. Engine.prototype._prepareWorkingCanvas = function () {
  12384. if (this._workingCanvas) {
  12385. return;
  12386. }
  12387. this._workingCanvas = document.createElement("canvas");
  12388. var context = this._workingCanvas.getContext("2d");
  12389. if (context) {
  12390. this._workingContext = context;
  12391. }
  12392. };
  12393. /**
  12394. * Reset the texture cache to empty state
  12395. */
  12396. Engine.prototype.resetTextureCache = function () {
  12397. for (var key in this._boundTexturesCache) {
  12398. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12399. continue;
  12400. }
  12401. var boundTexture = this._boundTexturesCache[key];
  12402. if (boundTexture) {
  12403. this._removeDesignatedSlot(boundTexture);
  12404. }
  12405. this._boundTexturesCache[key] = null;
  12406. }
  12407. if (!this.disableTextureBindingOptimization) {
  12408. this._nextFreeTextureSlots = [];
  12409. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12410. this._nextFreeTextureSlots.push(slot);
  12411. }
  12412. }
  12413. this._currentTextureChannel = -1;
  12414. };
  12415. /**
  12416. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12417. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12418. * @returns true if engine is in deterministic lock step mode
  12419. */
  12420. Engine.prototype.isDeterministicLockStep = function () {
  12421. return this._deterministicLockstep;
  12422. };
  12423. /**
  12424. * Gets the max steps when engine is running in deterministic lock step
  12425. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12426. * @returns the max steps
  12427. */
  12428. Engine.prototype.getLockstepMaxSteps = function () {
  12429. return this._lockstepMaxSteps;
  12430. };
  12431. /**
  12432. * Gets an object containing information about the current webGL context
  12433. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12434. */
  12435. Engine.prototype.getGlInfo = function () {
  12436. return {
  12437. vendor: this._glVendor,
  12438. renderer: this._glRenderer,
  12439. version: this._glVersion
  12440. };
  12441. };
  12442. /**
  12443. * Gets current aspect ratio
  12444. * @param camera defines the camera to use to get the aspect ratio
  12445. * @param useScreen defines if screen size must be used (or the current render target if any)
  12446. * @returns a number defining the aspect ratio
  12447. */
  12448. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12449. if (useScreen === void 0) { useScreen = false; }
  12450. var viewport = camera.viewport;
  12451. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12452. };
  12453. /**
  12454. * Gets current screen aspect ratio
  12455. * @returns a number defining the aspect ratio
  12456. */
  12457. Engine.prototype.getScreenAspectRatio = function () {
  12458. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12459. };
  12460. /**
  12461. * Gets the current render width
  12462. * @param useScreen defines if screen size must be used (or the current render target if any)
  12463. * @returns a number defining the current render width
  12464. */
  12465. Engine.prototype.getRenderWidth = function (useScreen) {
  12466. if (useScreen === void 0) { useScreen = false; }
  12467. if (!useScreen && this._currentRenderTarget) {
  12468. return this._currentRenderTarget.width;
  12469. }
  12470. return this._gl.drawingBufferWidth;
  12471. };
  12472. /**
  12473. * Gets the current render height
  12474. * @param useScreen defines if screen size must be used (or the current render target if any)
  12475. * @returns a number defining the current render height
  12476. */
  12477. Engine.prototype.getRenderHeight = function (useScreen) {
  12478. if (useScreen === void 0) { useScreen = false; }
  12479. if (!useScreen && this._currentRenderTarget) {
  12480. return this._currentRenderTarget.height;
  12481. }
  12482. return this._gl.drawingBufferHeight;
  12483. };
  12484. /**
  12485. * Gets the HTML canvas attached with the current webGL context
  12486. * @returns a HTML canvas
  12487. */
  12488. Engine.prototype.getRenderingCanvas = function () {
  12489. return this._renderingCanvas;
  12490. };
  12491. /**
  12492. * Gets the client rect of the HTML canvas attached with the current webGL context
  12493. * @returns a client rectanglee
  12494. */
  12495. Engine.prototype.getRenderingCanvasClientRect = function () {
  12496. if (!this._renderingCanvas) {
  12497. return null;
  12498. }
  12499. return this._renderingCanvas.getBoundingClientRect();
  12500. };
  12501. /**
  12502. * Defines the hardware scaling level.
  12503. * By default the hardware scaling level is computed from the window device ratio.
  12504. * 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.
  12505. * @param level defines the level to use
  12506. */
  12507. Engine.prototype.setHardwareScalingLevel = function (level) {
  12508. this._hardwareScalingLevel = level;
  12509. this.resize();
  12510. };
  12511. /**
  12512. * Gets the current hardware scaling level.
  12513. * By default the hardware scaling level is computed from the window device ratio.
  12514. * 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.
  12515. * @returns a number indicating the current hardware scaling level
  12516. */
  12517. Engine.prototype.getHardwareScalingLevel = function () {
  12518. return this._hardwareScalingLevel;
  12519. };
  12520. /**
  12521. * Gets the list of loaded textures
  12522. * @returns an array containing all loaded textures
  12523. */
  12524. Engine.prototype.getLoadedTexturesCache = function () {
  12525. return this._internalTexturesCache;
  12526. };
  12527. /**
  12528. * Gets the object containing all engine capabilities
  12529. * @returns the EngineCapabilities object
  12530. */
  12531. Engine.prototype.getCaps = function () {
  12532. return this._caps;
  12533. };
  12534. Object.defineProperty(Engine.prototype, "drawCalls", {
  12535. /** @hidden */
  12536. get: function () {
  12537. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12538. return 0;
  12539. },
  12540. enumerable: true,
  12541. configurable: true
  12542. });
  12543. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12544. /** @hidden */
  12545. get: function () {
  12546. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12547. return null;
  12548. },
  12549. enumerable: true,
  12550. configurable: true
  12551. });
  12552. /**
  12553. * Gets the current depth function
  12554. * @returns a number defining the depth function
  12555. */
  12556. Engine.prototype.getDepthFunction = function () {
  12557. return this._depthCullingState.depthFunc;
  12558. };
  12559. /**
  12560. * Sets the current depth function
  12561. * @param depthFunc defines the function to use
  12562. */
  12563. Engine.prototype.setDepthFunction = function (depthFunc) {
  12564. this._depthCullingState.depthFunc = depthFunc;
  12565. };
  12566. /**
  12567. * Sets the current depth function to GREATER
  12568. */
  12569. Engine.prototype.setDepthFunctionToGreater = function () {
  12570. this._depthCullingState.depthFunc = this._gl.GREATER;
  12571. };
  12572. /**
  12573. * Sets the current depth function to GEQUAL
  12574. */
  12575. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12576. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12577. };
  12578. /**
  12579. * Sets the current depth function to LESS
  12580. */
  12581. Engine.prototype.setDepthFunctionToLess = function () {
  12582. this._depthCullingState.depthFunc = this._gl.LESS;
  12583. };
  12584. /**
  12585. * Sets the current depth function to LEQUAL
  12586. */
  12587. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12588. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12589. };
  12590. /**
  12591. * Gets a boolean indicating if stencil buffer is enabled
  12592. * @returns the current stencil buffer state
  12593. */
  12594. Engine.prototype.getStencilBuffer = function () {
  12595. return this._stencilState.stencilTest;
  12596. };
  12597. /**
  12598. * Enable or disable the stencil buffer
  12599. * @param enable defines if the stencil buffer must be enabled or disabled
  12600. */
  12601. Engine.prototype.setStencilBuffer = function (enable) {
  12602. this._stencilState.stencilTest = enable;
  12603. };
  12604. /**
  12605. * Gets the current stencil mask
  12606. * @returns a number defining the new stencil mask to use
  12607. */
  12608. Engine.prototype.getStencilMask = function () {
  12609. return this._stencilState.stencilMask;
  12610. };
  12611. /**
  12612. * Sets the current stencil mask
  12613. * @param mask defines the new stencil mask to use
  12614. */
  12615. Engine.prototype.setStencilMask = function (mask) {
  12616. this._stencilState.stencilMask = mask;
  12617. };
  12618. /**
  12619. * Gets the current stencil function
  12620. * @returns a number defining the stencil function to use
  12621. */
  12622. Engine.prototype.getStencilFunction = function () {
  12623. return this._stencilState.stencilFunc;
  12624. };
  12625. /**
  12626. * Gets the current stencil reference value
  12627. * @returns a number defining the stencil reference value to use
  12628. */
  12629. Engine.prototype.getStencilFunctionReference = function () {
  12630. return this._stencilState.stencilFuncRef;
  12631. };
  12632. /**
  12633. * Gets the current stencil mask
  12634. * @returns a number defining the stencil mask to use
  12635. */
  12636. Engine.prototype.getStencilFunctionMask = function () {
  12637. return this._stencilState.stencilFuncMask;
  12638. };
  12639. /**
  12640. * Sets the current stencil function
  12641. * @param stencilFunc defines the new stencil function to use
  12642. */
  12643. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12644. this._stencilState.stencilFunc = stencilFunc;
  12645. };
  12646. /**
  12647. * Sets the current stencil reference
  12648. * @param reference defines the new stencil reference to use
  12649. */
  12650. Engine.prototype.setStencilFunctionReference = function (reference) {
  12651. this._stencilState.stencilFuncRef = reference;
  12652. };
  12653. /**
  12654. * Sets the current stencil mask
  12655. * @param mask defines the new stencil mask to use
  12656. */
  12657. Engine.prototype.setStencilFunctionMask = function (mask) {
  12658. this._stencilState.stencilFuncMask = mask;
  12659. };
  12660. /**
  12661. * Gets the current stencil operation when stencil fails
  12662. * @returns a number defining stencil operation to use when stencil fails
  12663. */
  12664. Engine.prototype.getStencilOperationFail = function () {
  12665. return this._stencilState.stencilOpStencilFail;
  12666. };
  12667. /**
  12668. * Gets the current stencil operation when depth fails
  12669. * @returns a number defining stencil operation to use when depth fails
  12670. */
  12671. Engine.prototype.getStencilOperationDepthFail = function () {
  12672. return this._stencilState.stencilOpDepthFail;
  12673. };
  12674. /**
  12675. * Gets the current stencil operation when stencil passes
  12676. * @returns a number defining stencil operation to use when stencil passes
  12677. */
  12678. Engine.prototype.getStencilOperationPass = function () {
  12679. return this._stencilState.stencilOpStencilDepthPass;
  12680. };
  12681. /**
  12682. * Sets the stencil operation to use when stencil fails
  12683. * @param operation defines the stencil operation to use when stencil fails
  12684. */
  12685. Engine.prototype.setStencilOperationFail = function (operation) {
  12686. this._stencilState.stencilOpStencilFail = operation;
  12687. };
  12688. /**
  12689. * Sets the stencil operation to use when depth fails
  12690. * @param operation defines the stencil operation to use when depth fails
  12691. */
  12692. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12693. this._stencilState.stencilOpDepthFail = operation;
  12694. };
  12695. /**
  12696. * Sets the stencil operation to use when stencil passes
  12697. * @param operation defines the stencil operation to use when stencil passes
  12698. */
  12699. Engine.prototype.setStencilOperationPass = function (operation) {
  12700. this._stencilState.stencilOpStencilDepthPass = operation;
  12701. };
  12702. /**
  12703. * Sets a boolean indicating if the dithering state is enabled or disabled
  12704. * @param value defines the dithering state
  12705. */
  12706. Engine.prototype.setDitheringState = function (value) {
  12707. if (value) {
  12708. this._gl.enable(this._gl.DITHER);
  12709. }
  12710. else {
  12711. this._gl.disable(this._gl.DITHER);
  12712. }
  12713. };
  12714. /**
  12715. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12716. * @param value defines the rasterizer state
  12717. */
  12718. Engine.prototype.setRasterizerState = function (value) {
  12719. if (value) {
  12720. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12721. }
  12722. else {
  12723. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12724. }
  12725. };
  12726. /**
  12727. * stop executing a render loop function and remove it from the execution array
  12728. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12729. */
  12730. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12731. if (!renderFunction) {
  12732. this._activeRenderLoops = [];
  12733. return;
  12734. }
  12735. var index = this._activeRenderLoops.indexOf(renderFunction);
  12736. if (index >= 0) {
  12737. this._activeRenderLoops.splice(index, 1);
  12738. }
  12739. };
  12740. /** @hidden */
  12741. Engine.prototype._renderLoop = function () {
  12742. if (!this._contextWasLost) {
  12743. var shouldRender = true;
  12744. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12745. shouldRender = false;
  12746. }
  12747. if (shouldRender) {
  12748. // Start new frame
  12749. this.beginFrame();
  12750. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12751. var renderFunction = this._activeRenderLoops[index];
  12752. renderFunction();
  12753. }
  12754. // Present
  12755. this.endFrame();
  12756. }
  12757. }
  12758. if (this._activeRenderLoops.length > 0) {
  12759. // Register new frame
  12760. var requester = null;
  12761. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12762. requester = this._vrDisplay;
  12763. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12764. }
  12765. else {
  12766. this._renderingQueueLaunched = false;
  12767. }
  12768. };
  12769. /**
  12770. * Register and execute a render loop. The engine can have more than one render function
  12771. * @param renderFunction defines the function to continuously execute
  12772. */
  12773. Engine.prototype.runRenderLoop = function (renderFunction) {
  12774. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12775. return;
  12776. }
  12777. this._activeRenderLoops.push(renderFunction);
  12778. if (!this._renderingQueueLaunched) {
  12779. this._renderingQueueLaunched = true;
  12780. this._bindedRenderFunction = this._renderLoop.bind(this);
  12781. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12782. }
  12783. };
  12784. /**
  12785. * Toggle full screen mode
  12786. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12787. * @param options defines an option object to be sent to the requestFullscreen function
  12788. */
  12789. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12790. if (this.isFullscreen) {
  12791. BABYLON.Tools.ExitFullscreen();
  12792. }
  12793. else {
  12794. this._pointerLockRequested = requestPointerLock;
  12795. if (this._renderingCanvas) {
  12796. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12797. }
  12798. }
  12799. };
  12800. /**
  12801. * Clear the current render buffer or the current render target (if any is set up)
  12802. * @param color defines the color to use
  12803. * @param backBuffer defines if the back buffer must be cleared
  12804. * @param depth defines if the depth buffer must be cleared
  12805. * @param stencil defines if the stencil buffer must be cleared
  12806. */
  12807. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12808. if (stencil === void 0) { stencil = false; }
  12809. this.applyStates();
  12810. var mode = 0;
  12811. if (backBuffer && color) {
  12812. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12813. mode |= this._gl.COLOR_BUFFER_BIT;
  12814. }
  12815. if (depth) {
  12816. this._gl.clearDepth(1.0);
  12817. mode |= this._gl.DEPTH_BUFFER_BIT;
  12818. }
  12819. if (stencil) {
  12820. this._gl.clearStencil(0);
  12821. mode |= this._gl.STENCIL_BUFFER_BIT;
  12822. }
  12823. this._gl.clear(mode);
  12824. };
  12825. /**
  12826. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12827. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12828. * @param y defines the y-coordinate of the corner of the clear rectangle
  12829. * @param width defines the width of the clear rectangle
  12830. * @param height defines the height of the clear rectangle
  12831. * @param clearColor defines the clear color
  12832. */
  12833. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12834. var gl = this._gl;
  12835. // Save state
  12836. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12837. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12838. // Change state
  12839. gl.enable(gl.SCISSOR_TEST);
  12840. gl.scissor(x, y, width, height);
  12841. // Clear
  12842. this.clear(clearColor, true, true, true);
  12843. // Restore state
  12844. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12845. if (curScissor === true) {
  12846. gl.enable(gl.SCISSOR_TEST);
  12847. }
  12848. else {
  12849. gl.disable(gl.SCISSOR_TEST);
  12850. }
  12851. };
  12852. /**
  12853. * Set the WebGL's viewport
  12854. * @param viewport defines the viewport element to be used
  12855. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12856. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12857. */
  12858. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12859. var width = requiredWidth || this.getRenderWidth();
  12860. var height = requiredHeight || this.getRenderHeight();
  12861. var x = viewport.x || 0;
  12862. var y = viewport.y || 0;
  12863. this._cachedViewport = viewport;
  12864. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12865. };
  12866. /**
  12867. * Directly set the WebGL Viewport
  12868. * @param x defines the x coordinate of the viewport (in screen space)
  12869. * @param y defines the y coordinate of the viewport (in screen space)
  12870. * @param width defines the width of the viewport (in screen space)
  12871. * @param height defines the height of the viewport (in screen space)
  12872. * @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
  12873. */
  12874. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12875. var currentViewport = this._cachedViewport;
  12876. this._cachedViewport = null;
  12877. this._gl.viewport(x, y, width, height);
  12878. return currentViewport;
  12879. };
  12880. /**
  12881. * Begin a new frame
  12882. */
  12883. Engine.prototype.beginFrame = function () {
  12884. this.onBeginFrameObservable.notifyObservers(this);
  12885. this._measureFps();
  12886. };
  12887. /**
  12888. * Enf the current frame
  12889. */
  12890. Engine.prototype.endFrame = function () {
  12891. // Force a flush in case we are using a bad OS.
  12892. if (this._badOS) {
  12893. this.flushFramebuffer();
  12894. }
  12895. // Submit frame to the vr device, if enabled
  12896. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12897. // TODO: We should only submit the frame if we read frameData successfully.
  12898. this._vrDisplay.submitFrame();
  12899. }
  12900. this.onEndFrameObservable.notifyObservers(this);
  12901. };
  12902. /**
  12903. * Resize the view according to the canvas' size
  12904. */
  12905. Engine.prototype.resize = function () {
  12906. // We're not resizing the size of the canvas while in VR mode & presenting
  12907. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12908. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12909. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12910. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12911. }
  12912. };
  12913. /**
  12914. * Force a specific size of the canvas
  12915. * @param width defines the new canvas' width
  12916. * @param height defines the new canvas' height
  12917. */
  12918. Engine.prototype.setSize = function (width, height) {
  12919. if (!this._renderingCanvas) {
  12920. return;
  12921. }
  12922. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12923. return;
  12924. }
  12925. this._renderingCanvas.width = width;
  12926. this._renderingCanvas.height = height;
  12927. for (var index = 0; index < this.scenes.length; index++) {
  12928. var scene = this.scenes[index];
  12929. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12930. var cam = scene.cameras[camIndex];
  12931. cam._currentRenderId = 0;
  12932. }
  12933. }
  12934. if (this.onResizeObservable.hasObservers) {
  12935. this.onResizeObservable.notifyObservers(this);
  12936. }
  12937. };
  12938. // WebVR functions
  12939. /**
  12940. * Gets a boolean indicating if a webVR device was detected
  12941. * @returns true if a webVR device was detected
  12942. */
  12943. Engine.prototype.isVRDevicePresent = function () {
  12944. return !!this._vrDisplay;
  12945. };
  12946. /**
  12947. * Gets the current webVR device
  12948. * @returns the current webVR device (or null)
  12949. */
  12950. Engine.prototype.getVRDevice = function () {
  12951. return this._vrDisplay;
  12952. };
  12953. /**
  12954. * Initializes a webVR display and starts listening to display change events
  12955. * The onVRDisplayChangedObservable will be notified upon these changes
  12956. * @returns The onVRDisplayChangedObservable
  12957. */
  12958. Engine.prototype.initWebVR = function () {
  12959. this.initWebVRAsync();
  12960. return this.onVRDisplayChangedObservable;
  12961. };
  12962. /**
  12963. * Initializes a webVR display and starts listening to display change events
  12964. * The onVRDisplayChangedObservable will be notified upon these changes
  12965. * @returns A promise containing a VRDisplay and if vr is supported
  12966. */
  12967. Engine.prototype.initWebVRAsync = function () {
  12968. var _this = this;
  12969. var notifyObservers = function () {
  12970. var eventArgs = {
  12971. vrDisplay: _this._vrDisplay,
  12972. vrSupported: _this._vrSupported
  12973. };
  12974. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12975. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12976. };
  12977. if (!this._onVrDisplayConnect) {
  12978. this._onVrDisplayConnect = function (event) {
  12979. _this._vrDisplay = event.display;
  12980. notifyObservers();
  12981. };
  12982. this._onVrDisplayDisconnect = function () {
  12983. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12984. _this._vrDisplay = undefined;
  12985. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12986. notifyObservers();
  12987. };
  12988. this._onVrDisplayPresentChange = function () {
  12989. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12990. };
  12991. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12992. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12993. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12994. }
  12995. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12996. this._webVRInitPromise.then(notifyObservers);
  12997. return this._webVRInitPromise;
  12998. };
  12999. /**
  13000. * Call this function to switch to webVR mode
  13001. * Will do nothing if webVR is not supported or if there is no webVR device
  13002. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13003. */
  13004. Engine.prototype.enableVR = function () {
  13005. var _this = this;
  13006. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13007. var onResolved = function () {
  13008. _this.onVRRequestPresentComplete.notifyObservers(true);
  13009. _this._onVRFullScreenTriggered();
  13010. };
  13011. var onRejected = function () {
  13012. _this.onVRRequestPresentComplete.notifyObservers(false);
  13013. };
  13014. this.onVRRequestPresentStart.notifyObservers(this);
  13015. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13016. }
  13017. };
  13018. /**
  13019. * Call this function to leave webVR mode
  13020. * Will do nothing if webVR is not supported or if there is no webVR device
  13021. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13022. */
  13023. Engine.prototype.disableVR = function () {
  13024. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13025. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13026. }
  13027. };
  13028. Engine.prototype._getVRDisplaysAsync = function () {
  13029. var _this = this;
  13030. return new Promise(function (res, rej) {
  13031. if (navigator.getVRDisplays) {
  13032. navigator.getVRDisplays().then(function (devices) {
  13033. _this._vrSupported = true;
  13034. // note that devices may actually be an empty array. This is fine;
  13035. // we expect this._vrDisplay to be undefined in this case.
  13036. _this._vrDisplay = devices[0];
  13037. res({
  13038. vrDisplay: _this._vrDisplay,
  13039. vrSupported: _this._vrSupported
  13040. });
  13041. });
  13042. }
  13043. else {
  13044. _this._vrDisplay = undefined;
  13045. _this._vrSupported = false;
  13046. res({
  13047. vrDisplay: _this._vrDisplay,
  13048. vrSupported: _this._vrSupported
  13049. });
  13050. }
  13051. });
  13052. };
  13053. /**
  13054. * Binds the frame buffer to the specified texture.
  13055. * @param texture The texture to render to or null for the default canvas
  13056. * @param faceIndex The face of the texture to render to in case of cube texture
  13057. * @param requiredWidth The width of the target to render to
  13058. * @param requiredHeight The height of the target to render to
  13059. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13060. * @param depthStencilTexture The depth stencil texture to use to render
  13061. * @param lodLevel defines le lod level to bind to the frame buffer
  13062. */
  13063. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13064. if (lodLevel === void 0) { lodLevel = 0; }
  13065. if (this._currentRenderTarget) {
  13066. this.unBindFramebuffer(this._currentRenderTarget);
  13067. }
  13068. this._currentRenderTarget = texture;
  13069. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13070. var gl = this._gl;
  13071. if (texture.isCube) {
  13072. if (faceIndex === undefined) {
  13073. faceIndex = 0;
  13074. }
  13075. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13076. if (depthStencilTexture) {
  13077. if (depthStencilTexture._generateStencilBuffer) {
  13078. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13079. }
  13080. else {
  13081. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13082. }
  13083. }
  13084. }
  13085. if (this._cachedViewport && !forceFullscreenViewport) {
  13086. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13087. }
  13088. else {
  13089. if (!requiredWidth) {
  13090. requiredWidth = texture.width;
  13091. if (lodLevel) {
  13092. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13093. }
  13094. }
  13095. if (!requiredHeight) {
  13096. requiredHeight = texture.height;
  13097. if (lodLevel) {
  13098. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13099. }
  13100. }
  13101. gl.viewport(0, 0, requiredWidth, requiredHeight);
  13102. }
  13103. this.wipeCaches();
  13104. };
  13105. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13106. if (this._currentFramebuffer !== framebuffer) {
  13107. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13108. this._currentFramebuffer = framebuffer;
  13109. }
  13110. };
  13111. /**
  13112. * Unbind the current render target texture from the webGL context
  13113. * @param texture defines the render target texture to unbind
  13114. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13115. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13116. */
  13117. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13118. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13119. this._currentRenderTarget = null;
  13120. // If MSAA, we need to bitblt back to main texture
  13121. var gl = this._gl;
  13122. if (texture._MSAAFramebuffer) {
  13123. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13124. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13125. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13126. }
  13127. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13128. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13129. gl.generateMipmap(gl.TEXTURE_2D);
  13130. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13131. }
  13132. if (onBeforeUnbind) {
  13133. if (texture._MSAAFramebuffer) {
  13134. // Bind the correct framebuffer
  13135. this.bindUnboundFramebuffer(texture._framebuffer);
  13136. }
  13137. onBeforeUnbind();
  13138. }
  13139. this.bindUnboundFramebuffer(null);
  13140. };
  13141. /**
  13142. * Unbind a list of render target textures from the webGL context
  13143. * This is used only when drawBuffer extension or webGL2 are active
  13144. * @param textures defines the render target textures to unbind
  13145. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13146. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13147. */
  13148. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13149. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13150. this._currentRenderTarget = null;
  13151. // If MSAA, we need to bitblt back to main texture
  13152. var gl = this._gl;
  13153. if (textures[0]._MSAAFramebuffer) {
  13154. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13155. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13156. var attachments = textures[0]._attachments;
  13157. if (!attachments) {
  13158. attachments = new Array(textures.length);
  13159. textures[0]._attachments = attachments;
  13160. }
  13161. for (var i = 0; i < textures.length; i++) {
  13162. var texture = textures[i];
  13163. for (var j = 0; j < attachments.length; j++) {
  13164. attachments[j] = gl.NONE;
  13165. }
  13166. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13167. gl.readBuffer(attachments[i]);
  13168. gl.drawBuffers(attachments);
  13169. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13170. }
  13171. for (var i = 0; i < attachments.length; i++) {
  13172. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13173. }
  13174. gl.drawBuffers(attachments);
  13175. }
  13176. for (var i = 0; i < textures.length; i++) {
  13177. var texture = textures[i];
  13178. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13179. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13180. gl.generateMipmap(gl.TEXTURE_2D);
  13181. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13182. }
  13183. }
  13184. if (onBeforeUnbind) {
  13185. if (textures[0]._MSAAFramebuffer) {
  13186. // Bind the correct framebuffer
  13187. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13188. }
  13189. onBeforeUnbind();
  13190. }
  13191. this.bindUnboundFramebuffer(null);
  13192. };
  13193. /**
  13194. * Force the mipmap generation for the given render target texture
  13195. * @param texture defines the render target texture to use
  13196. */
  13197. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13198. if (texture.generateMipMaps) {
  13199. var gl = this._gl;
  13200. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13201. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13202. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13203. }
  13204. };
  13205. /**
  13206. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13207. */
  13208. Engine.prototype.flushFramebuffer = function () {
  13209. this._gl.flush();
  13210. };
  13211. /**
  13212. * Unbind the current render target and bind the default framebuffer
  13213. */
  13214. Engine.prototype.restoreDefaultFramebuffer = function () {
  13215. if (this._currentRenderTarget) {
  13216. this.unBindFramebuffer(this._currentRenderTarget);
  13217. }
  13218. else {
  13219. this.bindUnboundFramebuffer(null);
  13220. }
  13221. if (this._cachedViewport) {
  13222. this.setViewport(this._cachedViewport);
  13223. }
  13224. this.wipeCaches();
  13225. };
  13226. // UBOs
  13227. /**
  13228. * Create an uniform buffer
  13229. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13230. * @param elements defines the content of the uniform buffer
  13231. * @returns the webGL uniform buffer
  13232. */
  13233. Engine.prototype.createUniformBuffer = function (elements) {
  13234. var ubo = this._gl.createBuffer();
  13235. if (!ubo) {
  13236. throw new Error("Unable to create uniform buffer");
  13237. }
  13238. this.bindUniformBuffer(ubo);
  13239. if (elements instanceof Float32Array) {
  13240. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13241. }
  13242. else {
  13243. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13244. }
  13245. this.bindUniformBuffer(null);
  13246. ubo.references = 1;
  13247. return ubo;
  13248. };
  13249. /**
  13250. * Create a dynamic uniform buffer
  13251. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13252. * @param elements defines the content of the uniform buffer
  13253. * @returns the webGL uniform buffer
  13254. */
  13255. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13256. var ubo = this._gl.createBuffer();
  13257. if (!ubo) {
  13258. throw new Error("Unable to create dynamic uniform buffer");
  13259. }
  13260. this.bindUniformBuffer(ubo);
  13261. if (elements instanceof Float32Array) {
  13262. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13263. }
  13264. else {
  13265. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13266. }
  13267. this.bindUniformBuffer(null);
  13268. ubo.references = 1;
  13269. return ubo;
  13270. };
  13271. /**
  13272. * Update an existing uniform buffer
  13273. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13274. * @param uniformBuffer defines the target uniform buffer
  13275. * @param elements defines the content to update
  13276. * @param offset defines the offset in the uniform buffer where update should start
  13277. * @param count defines the size of the data to update
  13278. */
  13279. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13280. this.bindUniformBuffer(uniformBuffer);
  13281. if (offset === undefined) {
  13282. offset = 0;
  13283. }
  13284. if (count === undefined) {
  13285. if (elements instanceof Float32Array) {
  13286. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13287. }
  13288. else {
  13289. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13290. }
  13291. }
  13292. else {
  13293. if (elements instanceof Float32Array) {
  13294. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13295. }
  13296. else {
  13297. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13298. }
  13299. }
  13300. this.bindUniformBuffer(null);
  13301. };
  13302. // VBOs
  13303. Engine.prototype._resetVertexBufferBinding = function () {
  13304. this.bindArrayBuffer(null);
  13305. this._cachedVertexBuffers = null;
  13306. };
  13307. /**
  13308. * Creates a vertex buffer
  13309. * @param data the data for the vertex buffer
  13310. * @returns the new WebGL static buffer
  13311. */
  13312. Engine.prototype.createVertexBuffer = function (data) {
  13313. var vbo = this._gl.createBuffer();
  13314. if (!vbo) {
  13315. throw new Error("Unable to create vertex buffer");
  13316. }
  13317. this.bindArrayBuffer(vbo);
  13318. if (data instanceof Array) {
  13319. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13320. }
  13321. else {
  13322. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13323. }
  13324. this._resetVertexBufferBinding();
  13325. vbo.references = 1;
  13326. return vbo;
  13327. };
  13328. /**
  13329. * Creates a dynamic vertex buffer
  13330. * @param data the data for the dynamic vertex buffer
  13331. * @returns the new WebGL dynamic buffer
  13332. */
  13333. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13334. var vbo = this._gl.createBuffer();
  13335. if (!vbo) {
  13336. throw new Error("Unable to create dynamic vertex buffer");
  13337. }
  13338. this.bindArrayBuffer(vbo);
  13339. if (data instanceof Array) {
  13340. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13341. }
  13342. else {
  13343. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13344. }
  13345. this._resetVertexBufferBinding();
  13346. vbo.references = 1;
  13347. return vbo;
  13348. };
  13349. /**
  13350. * Update a dynamic index buffer
  13351. * @param indexBuffer defines the target index buffer
  13352. * @param indices defines the data to update
  13353. * @param offset defines the offset in the target index buffer where update should start
  13354. */
  13355. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13356. if (offset === void 0) { offset = 0; }
  13357. // Force cache update
  13358. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13359. this.bindIndexBuffer(indexBuffer);
  13360. var arrayBuffer;
  13361. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13362. arrayBuffer = indices;
  13363. }
  13364. else {
  13365. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13366. }
  13367. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13368. this._resetIndexBufferBinding();
  13369. };
  13370. /**
  13371. * Updates a dynamic vertex buffer.
  13372. * @param vertexBuffer the vertex buffer to update
  13373. * @param data the data used to update the vertex buffer
  13374. * @param byteOffset the byte offset of the data
  13375. * @param byteLength the byte length of the data
  13376. */
  13377. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13378. this.bindArrayBuffer(vertexBuffer);
  13379. if (byteOffset === undefined) {
  13380. byteOffset = 0;
  13381. }
  13382. if (byteLength === undefined) {
  13383. if (data instanceof Array) {
  13384. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13385. }
  13386. else {
  13387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13388. }
  13389. }
  13390. else {
  13391. if (data instanceof Array) {
  13392. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13393. }
  13394. else {
  13395. if (data instanceof ArrayBuffer) {
  13396. data = new Uint8Array(data, byteOffset, byteLength);
  13397. }
  13398. else {
  13399. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13400. }
  13401. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13402. }
  13403. }
  13404. this._resetVertexBufferBinding();
  13405. };
  13406. Engine.prototype._resetIndexBufferBinding = function () {
  13407. this.bindIndexBuffer(null);
  13408. this._cachedIndexBuffer = null;
  13409. };
  13410. /**
  13411. * Creates a new index buffer
  13412. * @param indices defines the content of the index buffer
  13413. * @param updatable defines if the index buffer must be updatable
  13414. * @returns a new webGL buffer
  13415. */
  13416. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13417. var vbo = this._gl.createBuffer();
  13418. if (!vbo) {
  13419. throw new Error("Unable to create index buffer");
  13420. }
  13421. this.bindIndexBuffer(vbo);
  13422. // Check for 32 bits indices
  13423. var arrayBuffer;
  13424. var need32Bits = false;
  13425. if (indices instanceof Uint16Array) {
  13426. arrayBuffer = indices;
  13427. }
  13428. else {
  13429. //check 32 bit support
  13430. if (this._caps.uintIndices) {
  13431. if (indices instanceof Uint32Array) {
  13432. arrayBuffer = indices;
  13433. need32Bits = true;
  13434. }
  13435. else {
  13436. //number[] or Int32Array, check if 32 bit is necessary
  13437. for (var index = 0; index < indices.length; index++) {
  13438. if (indices[index] > 65535) {
  13439. need32Bits = true;
  13440. break;
  13441. }
  13442. }
  13443. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13444. }
  13445. }
  13446. else {
  13447. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13448. arrayBuffer = new Uint16Array(indices);
  13449. }
  13450. }
  13451. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13452. this._resetIndexBufferBinding();
  13453. vbo.references = 1;
  13454. vbo.is32Bits = need32Bits;
  13455. return vbo;
  13456. };
  13457. /**
  13458. * Bind a webGL buffer to the webGL context
  13459. * @param buffer defines the buffer to bind
  13460. */
  13461. Engine.prototype.bindArrayBuffer = function (buffer) {
  13462. if (!this._vaoRecordInProgress) {
  13463. this._unbindVertexArrayObject();
  13464. }
  13465. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13466. };
  13467. /**
  13468. * Bind an uniform buffer to the current webGL context
  13469. * @param buffer defines the buffer to bind
  13470. */
  13471. Engine.prototype.bindUniformBuffer = function (buffer) {
  13472. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13473. };
  13474. /**
  13475. * Bind a buffer to the current webGL context at a given location
  13476. * @param buffer defines the buffer to bind
  13477. * @param location defines the index where to bind the buffer
  13478. */
  13479. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13480. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13481. };
  13482. /**
  13483. * Bind a specific block at a given index in a specific shader program
  13484. * @param shaderProgram defines the shader program
  13485. * @param blockName defines the block name
  13486. * @param index defines the index where to bind the block
  13487. */
  13488. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13489. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13490. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13491. };
  13492. ;
  13493. Engine.prototype.bindIndexBuffer = function (buffer) {
  13494. if (!this._vaoRecordInProgress) {
  13495. this._unbindVertexArrayObject();
  13496. }
  13497. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13498. };
  13499. Engine.prototype.bindBuffer = function (buffer, target) {
  13500. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13501. this._gl.bindBuffer(target, buffer);
  13502. this._currentBoundBuffer[target] = buffer;
  13503. }
  13504. };
  13505. /**
  13506. * update the bound buffer with the given data
  13507. * @param data defines the data to update
  13508. */
  13509. Engine.prototype.updateArrayBuffer = function (data) {
  13510. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13511. };
  13512. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13513. var pointer = this._currentBufferPointers[indx];
  13514. var changed = false;
  13515. if (!pointer.active) {
  13516. changed = true;
  13517. pointer.active = true;
  13518. pointer.index = indx;
  13519. pointer.size = size;
  13520. pointer.type = type;
  13521. pointer.normalized = normalized;
  13522. pointer.stride = stride;
  13523. pointer.offset = offset;
  13524. pointer.buffer = buffer;
  13525. }
  13526. else {
  13527. if (pointer.buffer !== buffer) {
  13528. pointer.buffer = buffer;
  13529. changed = true;
  13530. }
  13531. if (pointer.size !== size) {
  13532. pointer.size = size;
  13533. changed = true;
  13534. }
  13535. if (pointer.type !== type) {
  13536. pointer.type = type;
  13537. changed = true;
  13538. }
  13539. if (pointer.normalized !== normalized) {
  13540. pointer.normalized = normalized;
  13541. changed = true;
  13542. }
  13543. if (pointer.stride !== stride) {
  13544. pointer.stride = stride;
  13545. changed = true;
  13546. }
  13547. if (pointer.offset !== offset) {
  13548. pointer.offset = offset;
  13549. changed = true;
  13550. }
  13551. }
  13552. if (changed || this._vaoRecordInProgress) {
  13553. this.bindArrayBuffer(buffer);
  13554. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13555. }
  13556. };
  13557. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13558. if (indexBuffer == null) {
  13559. return;
  13560. }
  13561. if (this._cachedIndexBuffer !== indexBuffer) {
  13562. this._cachedIndexBuffer = indexBuffer;
  13563. this.bindIndexBuffer(indexBuffer);
  13564. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13565. }
  13566. };
  13567. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13568. var attributes = effect.getAttributesNames();
  13569. if (!this._vaoRecordInProgress) {
  13570. this._unbindVertexArrayObject();
  13571. }
  13572. this.unbindAllAttributes();
  13573. for (var index = 0; index < attributes.length; index++) {
  13574. var order = effect.getAttributeLocation(index);
  13575. if (order >= 0) {
  13576. var vertexBuffer = vertexBuffers[attributes[index]];
  13577. if (!vertexBuffer) {
  13578. continue;
  13579. }
  13580. this._gl.enableVertexAttribArray(order);
  13581. if (!this._vaoRecordInProgress) {
  13582. this._vertexAttribArraysEnabled[order] = true;
  13583. }
  13584. var buffer = vertexBuffer.getBuffer();
  13585. if (buffer) {
  13586. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13587. if (vertexBuffer.getIsInstanced()) {
  13588. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13589. if (!this._vaoRecordInProgress) {
  13590. this._currentInstanceLocations.push(order);
  13591. this._currentInstanceBuffers.push(buffer);
  13592. }
  13593. }
  13594. }
  13595. }
  13596. }
  13597. };
  13598. /**
  13599. * Records a vertex array object
  13600. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13601. * @param vertexBuffers defines the list of vertex buffers to store
  13602. * @param indexBuffer defines the index buffer to store
  13603. * @param effect defines the effect to store
  13604. * @returns the new vertex array object
  13605. */
  13606. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13607. var vao = this._gl.createVertexArray();
  13608. this._vaoRecordInProgress = true;
  13609. this._gl.bindVertexArray(vao);
  13610. this._mustWipeVertexAttributes = true;
  13611. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13612. this.bindIndexBuffer(indexBuffer);
  13613. this._vaoRecordInProgress = false;
  13614. this._gl.bindVertexArray(null);
  13615. return vao;
  13616. };
  13617. /**
  13618. * Bind a specific vertex array object
  13619. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13620. * @param vertexArrayObject defines the vertex array object to bind
  13621. * @param indexBuffer defines the index buffer to bind
  13622. */
  13623. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13624. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13625. this._cachedVertexArrayObject = vertexArrayObject;
  13626. this._gl.bindVertexArray(vertexArrayObject);
  13627. this._cachedVertexBuffers = null;
  13628. this._cachedIndexBuffer = null;
  13629. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13630. this._mustWipeVertexAttributes = true;
  13631. }
  13632. };
  13633. /**
  13634. * Bind webGl buffers directly to the webGL context
  13635. * @param vertexBuffer defines the vertex buffer to bind
  13636. * @param indexBuffer defines the index buffer to bind
  13637. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13638. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13639. * @param effect defines the effect associated with the vertex buffer
  13640. */
  13641. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13642. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13643. this._cachedVertexBuffers = vertexBuffer;
  13644. this._cachedEffectForVertexBuffers = effect;
  13645. var attributesCount = effect.getAttributesCount();
  13646. this._unbindVertexArrayObject();
  13647. this.unbindAllAttributes();
  13648. var offset = 0;
  13649. for (var index = 0; index < attributesCount; index++) {
  13650. if (index < vertexDeclaration.length) {
  13651. var order = effect.getAttributeLocation(index);
  13652. if (order >= 0) {
  13653. this._gl.enableVertexAttribArray(order);
  13654. this._vertexAttribArraysEnabled[order] = true;
  13655. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13656. }
  13657. offset += vertexDeclaration[index] * 4;
  13658. }
  13659. }
  13660. }
  13661. this._bindIndexBufferWithCache(indexBuffer);
  13662. };
  13663. Engine.prototype._unbindVertexArrayObject = function () {
  13664. if (!this._cachedVertexArrayObject) {
  13665. return;
  13666. }
  13667. this._cachedVertexArrayObject = null;
  13668. this._gl.bindVertexArray(null);
  13669. };
  13670. /**
  13671. * Bind a list of vertex buffers to the webGL context
  13672. * @param vertexBuffers defines the list of vertex buffers to bind
  13673. * @param indexBuffer defines the index buffer to bind
  13674. * @param effect defines the effect associated with the vertex buffers
  13675. */
  13676. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13677. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13678. this._cachedVertexBuffers = vertexBuffers;
  13679. this._cachedEffectForVertexBuffers = effect;
  13680. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13681. }
  13682. this._bindIndexBufferWithCache(indexBuffer);
  13683. };
  13684. /**
  13685. * Unbind all instance attributes
  13686. */
  13687. Engine.prototype.unbindInstanceAttributes = function () {
  13688. var boundBuffer;
  13689. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13690. var instancesBuffer = this._currentInstanceBuffers[i];
  13691. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13692. boundBuffer = instancesBuffer;
  13693. this.bindArrayBuffer(instancesBuffer);
  13694. }
  13695. var offsetLocation = this._currentInstanceLocations[i];
  13696. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13697. }
  13698. this._currentInstanceBuffers.length = 0;
  13699. this._currentInstanceLocations.length = 0;
  13700. };
  13701. /**
  13702. * Release and free the memory of a vertex array object
  13703. * @param vao defines the vertex array object to delete
  13704. */
  13705. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13706. this._gl.deleteVertexArray(vao);
  13707. };
  13708. /** @hidden */
  13709. Engine.prototype._releaseBuffer = function (buffer) {
  13710. buffer.references--;
  13711. if (buffer.references === 0) {
  13712. this._gl.deleteBuffer(buffer);
  13713. return true;
  13714. }
  13715. return false;
  13716. };
  13717. /**
  13718. * Creates a webGL buffer to use with instanciation
  13719. * @param capacity defines the size of the buffer
  13720. * @returns the webGL buffer
  13721. */
  13722. Engine.prototype.createInstancesBuffer = function (capacity) {
  13723. var buffer = this._gl.createBuffer();
  13724. if (!buffer) {
  13725. throw new Error("Unable to create instance buffer");
  13726. }
  13727. buffer.capacity = capacity;
  13728. this.bindArrayBuffer(buffer);
  13729. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13730. return buffer;
  13731. };
  13732. /**
  13733. * Delete a webGL buffer used with instanciation
  13734. * @param buffer defines the webGL buffer to delete
  13735. */
  13736. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13737. this._gl.deleteBuffer(buffer);
  13738. };
  13739. /**
  13740. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13741. * @param instancesBuffer defines the webGL buffer to update and bind
  13742. * @param data defines the data to store in the buffer
  13743. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13744. */
  13745. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13746. this.bindArrayBuffer(instancesBuffer);
  13747. if (data) {
  13748. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13749. }
  13750. if (offsetLocations[0].index !== undefined) {
  13751. var stride = 0;
  13752. for (var i = 0; i < offsetLocations.length; i++) {
  13753. var ai = offsetLocations[i];
  13754. stride += ai.attributeSize * 4;
  13755. }
  13756. for (var i = 0; i < offsetLocations.length; i++) {
  13757. var ai = offsetLocations[i];
  13758. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13759. this._gl.enableVertexAttribArray(ai.index);
  13760. this._vertexAttribArraysEnabled[ai.index] = true;
  13761. }
  13762. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13763. this._gl.vertexAttribDivisor(ai.index, 1);
  13764. this._currentInstanceLocations.push(ai.index);
  13765. this._currentInstanceBuffers.push(instancesBuffer);
  13766. }
  13767. }
  13768. else {
  13769. for (var index = 0; index < 4; index++) {
  13770. var offsetLocation = offsetLocations[index];
  13771. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13772. this._gl.enableVertexAttribArray(offsetLocation);
  13773. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13774. }
  13775. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13776. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13777. this._currentInstanceLocations.push(offsetLocation);
  13778. this._currentInstanceBuffers.push(instancesBuffer);
  13779. }
  13780. }
  13781. };
  13782. /**
  13783. * Apply all cached states (depth, culling, stencil and alpha)
  13784. */
  13785. Engine.prototype.applyStates = function () {
  13786. this._depthCullingState.apply(this._gl);
  13787. this._stencilState.apply(this._gl);
  13788. this._alphaState.apply(this._gl);
  13789. };
  13790. /**
  13791. * Send a draw order
  13792. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13793. * @param indexStart defines the starting index
  13794. * @param indexCount defines the number of index to draw
  13795. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13796. */
  13797. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13798. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13799. };
  13800. /**
  13801. * Draw a list of points
  13802. * @param verticesStart defines the index of first vertex to draw
  13803. * @param verticesCount defines the count of vertices to draw
  13804. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13805. */
  13806. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13807. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13808. };
  13809. /**
  13810. * Draw a list of unindexed primitives
  13811. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13812. * @param verticesStart defines the index of first vertex to draw
  13813. * @param verticesCount defines the count of vertices to draw
  13814. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13815. */
  13816. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13817. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13818. };
  13819. /**
  13820. * Draw a list of indexed primitives
  13821. * @param fillMode defines the primitive to use
  13822. * @param indexStart defines the starting index
  13823. * @param indexCount defines the number of index to draw
  13824. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13825. */
  13826. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13827. // Apply states
  13828. this.applyStates();
  13829. this._drawCalls.addCount(1, false);
  13830. // Render
  13831. var drawMode = this._drawMode(fillMode);
  13832. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13833. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13834. if (instancesCount) {
  13835. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13836. }
  13837. else {
  13838. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13839. }
  13840. };
  13841. /**
  13842. * Draw a list of unindexed primitives
  13843. * @param fillMode defines the primitive to use
  13844. * @param verticesStart defines the index of first vertex to draw
  13845. * @param verticesCount defines the count of vertices to draw
  13846. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13847. */
  13848. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13849. // Apply states
  13850. this.applyStates();
  13851. this._drawCalls.addCount(1, false);
  13852. var drawMode = this._drawMode(fillMode);
  13853. if (instancesCount) {
  13854. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13855. }
  13856. else {
  13857. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13858. }
  13859. };
  13860. Engine.prototype._drawMode = function (fillMode) {
  13861. switch (fillMode) {
  13862. // Triangle views
  13863. case BABYLON.Material.TriangleFillMode:
  13864. return this._gl.TRIANGLES;
  13865. case BABYLON.Material.PointFillMode:
  13866. return this._gl.POINTS;
  13867. case BABYLON.Material.WireFrameFillMode:
  13868. return this._gl.LINES;
  13869. // Draw modes
  13870. case BABYLON.Material.PointListDrawMode:
  13871. return this._gl.POINTS;
  13872. case BABYLON.Material.LineListDrawMode:
  13873. return this._gl.LINES;
  13874. case BABYLON.Material.LineLoopDrawMode:
  13875. return this._gl.LINE_LOOP;
  13876. case BABYLON.Material.LineStripDrawMode:
  13877. return this._gl.LINE_STRIP;
  13878. case BABYLON.Material.TriangleStripDrawMode:
  13879. return this._gl.TRIANGLE_STRIP;
  13880. case BABYLON.Material.TriangleFanDrawMode:
  13881. return this._gl.TRIANGLE_FAN;
  13882. default:
  13883. return this._gl.TRIANGLES;
  13884. }
  13885. };
  13886. // Shaders
  13887. /** @hidden */
  13888. Engine.prototype._releaseEffect = function (effect) {
  13889. if (this._compiledEffects[effect._key]) {
  13890. delete this._compiledEffects[effect._key];
  13891. this._deleteProgram(effect.getProgram());
  13892. }
  13893. };
  13894. /** @hidden */
  13895. Engine.prototype._deleteProgram = function (program) {
  13896. if (program) {
  13897. program.__SPECTOR_rebuildProgram = null;
  13898. if (program.transformFeedback) {
  13899. this.deleteTransformFeedback(program.transformFeedback);
  13900. program.transformFeedback = null;
  13901. }
  13902. this._gl.deleteProgram(program);
  13903. }
  13904. };
  13905. /**
  13906. * Create a new effect (used to store vertex/fragment shaders)
  13907. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13908. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13909. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13910. * @param samplers defines an array of string used to represent textures
  13911. * @param defines defines the string containing the defines to use to compile the shaders
  13912. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13913. * @param onCompiled defines a function to call when the effect creation is successful
  13914. * @param onError defines a function to call when the effect creation has failed
  13915. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13916. * @returns the new Effect
  13917. */
  13918. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13919. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13920. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13921. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13922. if (this._compiledEffects[name]) {
  13923. var compiledEffect = this._compiledEffects[name];
  13924. if (onCompiled && compiledEffect.isReady()) {
  13925. onCompiled(compiledEffect);
  13926. }
  13927. return compiledEffect;
  13928. }
  13929. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13930. effect._key = name;
  13931. this._compiledEffects[name] = effect;
  13932. return effect;
  13933. };
  13934. /**
  13935. * Create an effect to use with particle systems
  13936. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13937. * @param uniformsNames defines a list of attribute names
  13938. * @param samplers defines an array of string used to represent textures
  13939. * @param defines defines the string containing the defines to use to compile the shaders
  13940. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13941. * @param onCompiled defines a function to call when the effect creation is successful
  13942. * @param onError defines a function to call when the effect creation has failed
  13943. * @returns the new Effect
  13944. */
  13945. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13946. if (uniformsNames === void 0) { uniformsNames = []; }
  13947. if (samplers === void 0) { samplers = []; }
  13948. if (defines === void 0) { defines = ""; }
  13949. return this.createEffect({
  13950. vertex: "particles",
  13951. fragmentElement: fragmentName
  13952. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13953. };
  13954. /**
  13955. * Directly creates a webGL program
  13956. * @param vertexCode defines the vertex shader code to use
  13957. * @param fragmentCode defines the fragment shader code to use
  13958. * @param context defines the webGL context to use (if not set, the current one will be used)
  13959. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13960. * @returns the new webGL program
  13961. */
  13962. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13963. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13964. context = context || this._gl;
  13965. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13966. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13967. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13968. };
  13969. /**
  13970. * Creates a webGL program
  13971. * @param vertexCode defines the vertex shader code to use
  13972. * @param fragmentCode defines the fragment shader code to use
  13973. * @param defines defines the string containing the defines to use to compile the shaders
  13974. * @param context defines the webGL context to use (if not set, the current one will be used)
  13975. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13976. * @returns the new webGL program
  13977. */
  13978. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13979. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13980. context = context || this._gl;
  13981. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13982. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13983. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13984. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13985. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13986. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13987. return program;
  13988. };
  13989. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13990. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13991. var shaderProgram = context.createProgram();
  13992. if (!shaderProgram) {
  13993. throw new Error("Unable to create program");
  13994. }
  13995. context.attachShader(shaderProgram, vertexShader);
  13996. context.attachShader(shaderProgram, fragmentShader);
  13997. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13998. var transformFeedback = this.createTransformFeedback();
  13999. this.bindTransformFeedback(transformFeedback);
  14000. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14001. shaderProgram.transformFeedback = transformFeedback;
  14002. }
  14003. context.linkProgram(shaderProgram);
  14004. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14005. this.bindTransformFeedback(null);
  14006. }
  14007. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14008. if (!linked) {
  14009. context.validateProgram(shaderProgram);
  14010. var error = context.getProgramInfoLog(shaderProgram);
  14011. if (error) {
  14012. throw new Error(error);
  14013. }
  14014. }
  14015. context.deleteShader(vertexShader);
  14016. context.deleteShader(fragmentShader);
  14017. return shaderProgram;
  14018. };
  14019. /**
  14020. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14021. * @param shaderProgram defines the webGL program to use
  14022. * @param uniformsNames defines the list of uniform names
  14023. * @returns an array of webGL uniform locations
  14024. */
  14025. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14026. var results = new Array();
  14027. for (var index = 0; index < uniformsNames.length; index++) {
  14028. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14029. }
  14030. return results;
  14031. };
  14032. /**
  14033. * Gets the lsit of active attributes for a given webGL program
  14034. * @param shaderProgram defines the webGL program to use
  14035. * @param attributesNames defines the list of attribute names to get
  14036. * @returns an array of indices indicating the offset of each attribute
  14037. */
  14038. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14039. var results = [];
  14040. for (var index = 0; index < attributesNames.length; index++) {
  14041. try {
  14042. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14043. }
  14044. catch (e) {
  14045. results.push(-1);
  14046. }
  14047. }
  14048. return results;
  14049. };
  14050. /**
  14051. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14052. * @param effect defines the effect to activate
  14053. */
  14054. Engine.prototype.enableEffect = function (effect) {
  14055. if (!effect) {
  14056. return;
  14057. }
  14058. // Use program
  14059. this.bindSamplers(effect);
  14060. this._currentEffect = effect;
  14061. if (effect.onBind) {
  14062. effect.onBind(effect);
  14063. }
  14064. effect.onBindObservable.notifyObservers(effect);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to an array of int32
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param array defines the array of int32 to store
  14070. */
  14071. Engine.prototype.setIntArray = function (uniform, array) {
  14072. if (!uniform)
  14073. return;
  14074. this._gl.uniform1iv(uniform, array);
  14075. };
  14076. /**
  14077. * Set the value of an uniform to an array of int32 (stored as vec2)
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param array defines the array of int32 to store
  14080. */
  14081. Engine.prototype.setIntArray2 = function (uniform, array) {
  14082. if (!uniform || array.length % 2 !== 0)
  14083. return;
  14084. this._gl.uniform2iv(uniform, array);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to an array of int32 (stored as vec3)
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param array defines the array of int32 to store
  14090. */
  14091. Engine.prototype.setIntArray3 = function (uniform, array) {
  14092. if (!uniform || array.length % 3 !== 0)
  14093. return;
  14094. this._gl.uniform3iv(uniform, array);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to an array of int32 (stored as vec4)
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param array defines the array of int32 to store
  14100. */
  14101. Engine.prototype.setIntArray4 = function (uniform, array) {
  14102. if (!uniform || array.length % 4 !== 0)
  14103. return;
  14104. this._gl.uniform4iv(uniform, array);
  14105. };
  14106. /**
  14107. * Set the value of an uniform to an array of float32
  14108. * @param uniform defines the webGL uniform location where to store the value
  14109. * @param array defines the array of float32 to store
  14110. */
  14111. Engine.prototype.setFloatArray = function (uniform, array) {
  14112. if (!uniform)
  14113. return;
  14114. this._gl.uniform1fv(uniform, array);
  14115. };
  14116. /**
  14117. * Set the value of an uniform to an array of float32 (stored as vec2)
  14118. * @param uniform defines the webGL uniform location where to store the value
  14119. * @param array defines the array of float32 to store
  14120. */
  14121. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14122. if (!uniform || array.length % 2 !== 0)
  14123. return;
  14124. this._gl.uniform2fv(uniform, array);
  14125. };
  14126. /**
  14127. * Set the value of an uniform to an array of float32 (stored as vec3)
  14128. * @param uniform defines the webGL uniform location where to store the value
  14129. * @param array defines the array of float32 to store
  14130. */
  14131. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14132. if (!uniform || array.length % 3 !== 0)
  14133. return;
  14134. this._gl.uniform3fv(uniform, array);
  14135. };
  14136. /**
  14137. * Set the value of an uniform to an array of float32 (stored as vec4)
  14138. * @param uniform defines the webGL uniform location where to store the value
  14139. * @param array defines the array of float32 to store
  14140. */
  14141. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14142. if (!uniform || array.length % 4 !== 0)
  14143. return;
  14144. this._gl.uniform4fv(uniform, array);
  14145. };
  14146. /**
  14147. * Set the value of an uniform to an array of number
  14148. * @param uniform defines the webGL uniform location where to store the value
  14149. * @param array defines the array of number to store
  14150. */
  14151. Engine.prototype.setArray = function (uniform, array) {
  14152. if (!uniform)
  14153. return;
  14154. this._gl.uniform1fv(uniform, array);
  14155. };
  14156. /**
  14157. * Set the value of an uniform to an array of number (stored as vec2)
  14158. * @param uniform defines the webGL uniform location where to store the value
  14159. * @param array defines the array of number to store
  14160. */
  14161. Engine.prototype.setArray2 = function (uniform, array) {
  14162. if (!uniform || array.length % 2 !== 0)
  14163. return;
  14164. this._gl.uniform2fv(uniform, array);
  14165. };
  14166. /**
  14167. * Set the value of an uniform to an array of number (stored as vec3)
  14168. * @param uniform defines the webGL uniform location where to store the value
  14169. * @param array defines the array of number to store
  14170. */
  14171. Engine.prototype.setArray3 = function (uniform, array) {
  14172. if (!uniform || array.length % 3 !== 0)
  14173. return;
  14174. this._gl.uniform3fv(uniform, array);
  14175. };
  14176. /**
  14177. * Set the value of an uniform to an array of number (stored as vec4)
  14178. * @param uniform defines the webGL uniform location where to store the value
  14179. * @param array defines the array of number to store
  14180. */
  14181. Engine.prototype.setArray4 = function (uniform, array) {
  14182. if (!uniform || array.length % 4 !== 0)
  14183. return;
  14184. this._gl.uniform4fv(uniform, array);
  14185. };
  14186. /**
  14187. * Set the value of an uniform to an array of float32 (stored as matrices)
  14188. * @param uniform defines the webGL uniform location where to store the value
  14189. * @param matrices defines the array of float32 to store
  14190. */
  14191. Engine.prototype.setMatrices = function (uniform, matrices) {
  14192. if (!uniform)
  14193. return;
  14194. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14195. };
  14196. /**
  14197. * Set the value of an uniform to a matrix
  14198. * @param uniform defines the webGL uniform location where to store the value
  14199. * @param matrix defines the matrix to store
  14200. */
  14201. Engine.prototype.setMatrix = function (uniform, matrix) {
  14202. if (!uniform)
  14203. return;
  14204. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14205. };
  14206. /**
  14207. * Set the value of an uniform to a matrix (3x3)
  14208. * @param uniform defines the webGL uniform location where to store the value
  14209. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14210. */
  14211. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14212. if (!uniform)
  14213. return;
  14214. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14215. };
  14216. /**
  14217. * Set the value of an uniform to a matrix (2x2)
  14218. * @param uniform defines the webGL uniform location where to store the value
  14219. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14220. */
  14221. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14222. if (!uniform)
  14223. return;
  14224. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14225. };
  14226. /**
  14227. * Set the value of an uniform to a number (int)
  14228. * @param uniform defines the webGL uniform location where to store the value
  14229. * @param value defines the int number to store
  14230. */
  14231. Engine.prototype.setInt = function (uniform, value) {
  14232. if (!uniform)
  14233. return;
  14234. this._gl.uniform1i(uniform, value);
  14235. };
  14236. /**
  14237. * Set the value of an uniform to a number (float)
  14238. * @param uniform defines the webGL uniform location where to store the value
  14239. * @param value defines the float number to store
  14240. */
  14241. Engine.prototype.setFloat = function (uniform, value) {
  14242. if (!uniform)
  14243. return;
  14244. this._gl.uniform1f(uniform, value);
  14245. };
  14246. /**
  14247. * Set the value of an uniform to a vec2
  14248. * @param uniform defines the webGL uniform location where to store the value
  14249. * @param x defines the 1st component of the value
  14250. * @param y defines the 2nd component of the value
  14251. */
  14252. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14253. if (!uniform)
  14254. return;
  14255. this._gl.uniform2f(uniform, x, y);
  14256. };
  14257. /**
  14258. * Set the value of an uniform to a vec3
  14259. * @param uniform defines the webGL uniform location where to store the value
  14260. * @param x defines the 1st component of the value
  14261. * @param y defines the 2nd component of the value
  14262. * @param z defines the 3rd component of the value
  14263. */
  14264. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14265. if (!uniform)
  14266. return;
  14267. this._gl.uniform3f(uniform, x, y, z);
  14268. };
  14269. /**
  14270. * Set the value of an uniform to a boolean
  14271. * @param uniform defines the webGL uniform location where to store the value
  14272. * @param bool defines the boolean to store
  14273. */
  14274. Engine.prototype.setBool = function (uniform, bool) {
  14275. if (!uniform)
  14276. return;
  14277. this._gl.uniform1i(uniform, bool);
  14278. };
  14279. /**
  14280. * Set the value of an uniform to a vec4
  14281. * @param uniform defines the webGL uniform location where to store the value
  14282. * @param x defines the 1st component of the value
  14283. * @param y defines the 2nd component of the value
  14284. * @param z defines the 3rd component of the value
  14285. * @param w defines the 4th component of the value
  14286. */
  14287. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14288. if (!uniform)
  14289. return;
  14290. this._gl.uniform4f(uniform, x, y, z, w);
  14291. };
  14292. /**
  14293. * Set the value of an uniform to a Color3
  14294. * @param uniform defines the webGL uniform location where to store the value
  14295. * @param color3 defines the color to store
  14296. */
  14297. Engine.prototype.setColor3 = function (uniform, color3) {
  14298. if (!uniform)
  14299. return;
  14300. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14301. };
  14302. /**
  14303. * Set the value of an uniform to a Color3 and an alpha value
  14304. * @param uniform defines the webGL uniform location where to store the value
  14305. * @param color3 defines the color to store
  14306. * @param alpha defines the alpha component to store
  14307. */
  14308. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14309. if (!uniform)
  14310. return;
  14311. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14312. };
  14313. /**
  14314. * Sets a Color4 on a uniform variable
  14315. * @param uniform defines the uniform location
  14316. * @param color4 defines the value to be set
  14317. */
  14318. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14319. if (!uniform)
  14320. return;
  14321. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14322. };
  14323. // States
  14324. /**
  14325. * Set various states to the webGL context
  14326. * @param culling defines backface culling state
  14327. * @param zOffset defines the value to apply to zOffset (0 by default)
  14328. * @param force defines if states must be applied even if cache is up to date
  14329. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14330. */
  14331. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14332. if (zOffset === void 0) { zOffset = 0; }
  14333. if (reverseSide === void 0) { reverseSide = false; }
  14334. // Culling
  14335. if (this._depthCullingState.cull !== culling || force) {
  14336. this._depthCullingState.cull = culling;
  14337. }
  14338. // Cull face
  14339. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14340. if (this._depthCullingState.cullFace !== cullFace || force) {
  14341. this._depthCullingState.cullFace = cullFace;
  14342. }
  14343. // Z offset
  14344. this.setZOffset(zOffset);
  14345. // Front face
  14346. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14347. if (this._depthCullingState.frontFace !== frontFace || force) {
  14348. this._depthCullingState.frontFace = frontFace;
  14349. }
  14350. };
  14351. /**
  14352. * Set the z offset to apply to current rendering
  14353. * @param value defines the offset to apply
  14354. */
  14355. Engine.prototype.setZOffset = function (value) {
  14356. this._depthCullingState.zOffset = value;
  14357. };
  14358. /**
  14359. * Gets the current value of the zOffset
  14360. * @returns the current zOffset state
  14361. */
  14362. Engine.prototype.getZOffset = function () {
  14363. return this._depthCullingState.zOffset;
  14364. };
  14365. /**
  14366. * Enable or disable depth buffering
  14367. * @param enable defines the state to set
  14368. */
  14369. Engine.prototype.setDepthBuffer = function (enable) {
  14370. this._depthCullingState.depthTest = enable;
  14371. };
  14372. /**
  14373. * Gets a boolean indicating if depth writing is enabled
  14374. * @returns the current depth writing state
  14375. */
  14376. Engine.prototype.getDepthWrite = function () {
  14377. return this._depthCullingState.depthMask;
  14378. };
  14379. /**
  14380. * Enable or disable depth writing
  14381. * @param enable defines the state to set
  14382. */
  14383. Engine.prototype.setDepthWrite = function (enable) {
  14384. this._depthCullingState.depthMask = enable;
  14385. };
  14386. /**
  14387. * Enable or disable color writing
  14388. * @param enable defines the state to set
  14389. */
  14390. Engine.prototype.setColorWrite = function (enable) {
  14391. this._gl.colorMask(enable, enable, enable, enable);
  14392. this._colorWrite = enable;
  14393. };
  14394. /**
  14395. * Gets a boolean indicating if color writing is enabled
  14396. * @returns the current color writing state
  14397. */
  14398. Engine.prototype.getColorWrite = function () {
  14399. return this._colorWrite;
  14400. };
  14401. /**
  14402. * Sets alpha constants used by some alpha blending modes
  14403. * @param r defines the red component
  14404. * @param g defines the green component
  14405. * @param b defines the blue component
  14406. * @param a defines the alpha component
  14407. */
  14408. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14409. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14410. };
  14411. /**
  14412. * Sets the current alpha mode
  14413. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14414. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14415. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14416. */
  14417. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14418. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14419. if (this._alphaMode === mode) {
  14420. return;
  14421. }
  14422. switch (mode) {
  14423. case Engine.ALPHA_DISABLE:
  14424. this._alphaState.alphaBlend = false;
  14425. break;
  14426. case Engine.ALPHA_PREMULTIPLIED:
  14427. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14428. this._alphaState.alphaBlend = true;
  14429. break;
  14430. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14431. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14432. this._alphaState.alphaBlend = true;
  14433. break;
  14434. case Engine.ALPHA_COMBINE:
  14435. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14436. this._alphaState.alphaBlend = true;
  14437. break;
  14438. case Engine.ALPHA_ONEONE:
  14439. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14440. this._alphaState.alphaBlend = true;
  14441. break;
  14442. case Engine.ALPHA_ADD:
  14443. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14444. this._alphaState.alphaBlend = true;
  14445. break;
  14446. case Engine.ALPHA_SUBTRACT:
  14447. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14448. this._alphaState.alphaBlend = true;
  14449. break;
  14450. case Engine.ALPHA_MULTIPLY:
  14451. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14452. this._alphaState.alphaBlend = true;
  14453. break;
  14454. case Engine.ALPHA_MAXIMIZED:
  14455. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14456. this._alphaState.alphaBlend = true;
  14457. break;
  14458. case Engine.ALPHA_INTERPOLATE:
  14459. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14460. this._alphaState.alphaBlend = true;
  14461. break;
  14462. case Engine.ALPHA_SCREENMODE:
  14463. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14464. this._alphaState.alphaBlend = true;
  14465. break;
  14466. }
  14467. if (!noDepthWriteChange) {
  14468. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14469. }
  14470. this._alphaMode = mode;
  14471. };
  14472. /**
  14473. * Gets the current alpha mode
  14474. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14475. * @returns the current alpha mode
  14476. */
  14477. Engine.prototype.getAlphaMode = function () {
  14478. return this._alphaMode;
  14479. };
  14480. // Textures
  14481. /**
  14482. * Force the entire cache to be cleared
  14483. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14484. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14485. */
  14486. Engine.prototype.wipeCaches = function (bruteForce) {
  14487. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14488. return;
  14489. }
  14490. this._currentEffect = null;
  14491. if (bruteForce) {
  14492. this.resetTextureCache();
  14493. this._currentProgram = null;
  14494. this._stencilState.reset();
  14495. this._depthCullingState.reset();
  14496. this.setDepthFunctionToLessOrEqual();
  14497. this._alphaState.reset();
  14498. }
  14499. this._resetVertexBufferBinding();
  14500. this._cachedIndexBuffer = null;
  14501. this._cachedEffectForVertexBuffers = null;
  14502. this._unbindVertexArrayObject();
  14503. this.bindIndexBuffer(null);
  14504. };
  14505. /**
  14506. * Set the compressed texture format to use, based on the formats you have, and the formats
  14507. * supported by the hardware / browser.
  14508. *
  14509. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14510. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14511. * to API arguments needed to compressed textures. This puts the burden on the container
  14512. * generator to house the arcane code for determining these for current & future formats.
  14513. *
  14514. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14515. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14516. *
  14517. * Note: The result of this call is not taken into account when a texture is base64.
  14518. *
  14519. * @param formatsAvailable defines the list of those format families you have created
  14520. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14521. *
  14522. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14523. * @returns The extension selected.
  14524. */
  14525. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14526. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14527. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14528. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14529. return this._textureFormatInUse = this._texturesSupported[i];
  14530. }
  14531. }
  14532. }
  14533. // actively set format to nothing, to allow this to be called more than once
  14534. // and possibly fail the 2nd time
  14535. this._textureFormatInUse = null;
  14536. return null;
  14537. };
  14538. /** @hidden */
  14539. Engine.prototype._createTexture = function () {
  14540. var texture = this._gl.createTexture();
  14541. if (!texture) {
  14542. throw new Error("Unable to create texture");
  14543. }
  14544. return texture;
  14545. };
  14546. /**
  14547. * Usually called from BABYLON.Texture.ts.
  14548. * Passed information to create a WebGLTexture
  14549. * @param urlArg defines a value which contains one of the following:
  14550. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14551. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14552. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14553. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14554. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14555. * @param scene needed for loading to the correct scene
  14556. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14557. * @param onLoad optional callback to be called upon successful completion
  14558. * @param onError optional callback to be called upon failure
  14559. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14560. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14561. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14562. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14563. */
  14564. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14565. var _this = this;
  14566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14567. if (onLoad === void 0) { onLoad = null; }
  14568. if (onError === void 0) { onError = null; }
  14569. if (buffer === void 0) { buffer = null; }
  14570. if (fallback === void 0) { fallback = null; }
  14571. if (format === void 0) { format = null; }
  14572. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14573. var fromData = url.substr(0, 5) === "data:";
  14574. var fromBlob = url.substr(0, 5) === "blob:";
  14575. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14576. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14577. // establish the file extension, if possible
  14578. var lastDot = url.lastIndexOf('.');
  14579. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14580. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14581. var isTGA = (extension.indexOf(".tga") === 0);
  14582. // determine if a ktx file should be substituted
  14583. var isKTX = false;
  14584. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14585. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14586. isKTX = true;
  14587. }
  14588. if (scene) {
  14589. scene._addPendingData(texture);
  14590. }
  14591. texture.url = url;
  14592. texture.generateMipMaps = !noMipmap;
  14593. texture.samplingMode = samplingMode;
  14594. texture.invertY = invertY;
  14595. if (!this._doNotHandleContextLost) {
  14596. // Keep a link to the buffer only if we plan to handle context lost
  14597. texture._buffer = buffer;
  14598. }
  14599. var onLoadObserver = null;
  14600. if (onLoad && !fallback) {
  14601. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14602. }
  14603. if (!fallback)
  14604. this._internalTexturesCache.push(texture);
  14605. var onerror = function (message, exception) {
  14606. if (scene) {
  14607. scene._removePendingData(texture);
  14608. }
  14609. if (onLoadObserver) {
  14610. texture.onLoadedObservable.remove(onLoadObserver);
  14611. }
  14612. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14613. if (isKTX) {
  14614. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14615. }
  14616. else if (BABYLON.Tools.UseFallbackTexture) {
  14617. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14618. }
  14619. if (onError) {
  14620. onError(message || "Unknown error", exception);
  14621. }
  14622. };
  14623. var callback = null;
  14624. // processing for non-image formats
  14625. if (isKTX || isTGA || isDDS) {
  14626. if (isKTX) {
  14627. callback = function (data) {
  14628. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14629. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14630. ktx.uploadLevels(_this._gl, !noMipmap);
  14631. return false;
  14632. }, samplingMode);
  14633. };
  14634. }
  14635. else if (isTGA) {
  14636. callback = function (arrayBuffer) {
  14637. var data = new Uint8Array(arrayBuffer);
  14638. var header = BABYLON.TGATools.GetTGAHeader(data);
  14639. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14640. BABYLON.TGATools.UploadContent(_this._gl, data);
  14641. return false;
  14642. }, samplingMode);
  14643. };
  14644. }
  14645. else if (isDDS) {
  14646. callback = function (data) {
  14647. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14648. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14649. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14650. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14651. return false;
  14652. }, samplingMode);
  14653. };
  14654. }
  14655. if (!buffer) {
  14656. this._loadFile(url, function (data) {
  14657. if (callback) {
  14658. callback(data);
  14659. }
  14660. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14661. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14662. });
  14663. }
  14664. else {
  14665. if (callback) {
  14666. callback(buffer);
  14667. }
  14668. }
  14669. // image format processing
  14670. }
  14671. else {
  14672. var onload = function (img) {
  14673. if (fromBlob && !_this._doNotHandleContextLost) {
  14674. // We need to store the image if we need to rebuild the texture
  14675. // in case of a webgl context lost
  14676. texture._buffer = img;
  14677. }
  14678. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14679. var gl = _this._gl;
  14680. var isPot = (img.width === potWidth && img.height === potHeight);
  14681. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14682. if (isPot) {
  14683. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14684. return false;
  14685. }
  14686. // Using shaders to rescale because canvas.drawImage is lossy
  14687. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14688. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14689. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14694. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14695. _this._releaseTexture(source);
  14696. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14697. continuationCallback();
  14698. });
  14699. return true;
  14700. }, samplingMode);
  14701. };
  14702. if (!fromData || isBase64) {
  14703. if (buffer instanceof HTMLImageElement) {
  14704. onload(buffer);
  14705. }
  14706. else {
  14707. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14708. }
  14709. }
  14710. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14711. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14712. }
  14713. else {
  14714. onload(buffer);
  14715. }
  14716. }
  14717. return texture;
  14718. };
  14719. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14720. var _this = this;
  14721. var rtt = this.createRenderTargetTexture({
  14722. width: destination.width,
  14723. height: destination.height,
  14724. }, {
  14725. generateMipMaps: false,
  14726. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14727. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14728. generateDepthBuffer: false,
  14729. generateStencilBuffer: false
  14730. });
  14731. if (!this._rescalePostProcess) {
  14732. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14733. }
  14734. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14735. _this._rescalePostProcess.onApply = function (effect) {
  14736. effect._bindTexture("textureSampler", source);
  14737. };
  14738. var hostingScene = scene;
  14739. if (!hostingScene) {
  14740. hostingScene = _this.scenes[_this.scenes.length - 1];
  14741. }
  14742. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14743. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14744. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14745. _this.unBindFramebuffer(rtt);
  14746. _this._releaseTexture(rtt);
  14747. if (onComplete) {
  14748. onComplete();
  14749. }
  14750. });
  14751. };
  14752. /**
  14753. * Update a raw texture
  14754. * @param texture defines the texture to update
  14755. * @param data defines the data to store in the texture
  14756. * @param format defines the format of the data
  14757. * @param invertY defines if data must be stored with Y axis inverted
  14758. * @param compression defines the compression used (null by default)
  14759. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14760. */
  14761. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14762. if (compression === void 0) { compression = null; }
  14763. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14764. if (!texture) {
  14765. return;
  14766. }
  14767. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14768. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14769. // babylon's internalFormat but gl's texImage2D format
  14770. var internalFormat = this._getInternalFormat(format);
  14771. var textureType = this._getWebGLTextureType(type);
  14772. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14773. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14774. if (!this._doNotHandleContextLost) {
  14775. texture._bufferView = data;
  14776. texture.format = format;
  14777. texture.type = type;
  14778. texture.invertY = invertY;
  14779. texture._compression = compression;
  14780. }
  14781. if (texture.width % 4 !== 0) {
  14782. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14783. }
  14784. if (compression && data) {
  14785. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14786. }
  14787. else {
  14788. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14789. }
  14790. if (texture.generateMipMaps) {
  14791. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14792. }
  14793. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14794. // this.resetTextureCache();
  14795. texture.isReady = true;
  14796. };
  14797. /**
  14798. * Creates a raw texture
  14799. * @param data defines the data to store in the texture
  14800. * @param width defines the width of the texture
  14801. * @param height defines the height of the texture
  14802. * @param format defines the format of the data
  14803. * @param generateMipMaps defines if the engine should generate the mip levels
  14804. * @param invertY defines if data must be stored with Y axis inverted
  14805. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14806. * @param compression defines the compression used (null by default)
  14807. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14808. * @returns the raw texture inside an InternalTexture
  14809. */
  14810. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14811. if (compression === void 0) { compression = null; }
  14812. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14813. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14814. texture.baseWidth = width;
  14815. texture.baseHeight = height;
  14816. texture.width = width;
  14817. texture.height = height;
  14818. texture.format = format;
  14819. texture.generateMipMaps = generateMipMaps;
  14820. texture.samplingMode = samplingMode;
  14821. texture.invertY = invertY;
  14822. texture._compression = compression;
  14823. texture.type = type;
  14824. if (!this._doNotHandleContextLost) {
  14825. texture._bufferView = data;
  14826. }
  14827. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14828. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14829. // Filters
  14830. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14831. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14832. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14833. if (generateMipMaps) {
  14834. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14835. }
  14836. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14837. this._internalTexturesCache.push(texture);
  14838. return texture;
  14839. };
  14840. /**
  14841. * Creates a dynamic texture
  14842. * @param width defines the width of the texture
  14843. * @param height defines the height of the texture
  14844. * @param generateMipMaps defines if the engine should generate the mip levels
  14845. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14846. * @returns the dynamic texture inside an InternalTexture
  14847. */
  14848. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14849. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14850. texture.baseWidth = width;
  14851. texture.baseHeight = height;
  14852. if (generateMipMaps) {
  14853. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14854. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14855. }
  14856. // this.resetTextureCache();
  14857. texture.width = width;
  14858. texture.height = height;
  14859. texture.isReady = false;
  14860. texture.generateMipMaps = generateMipMaps;
  14861. texture.samplingMode = samplingMode;
  14862. this.updateTextureSamplingMode(samplingMode, texture);
  14863. this._internalTexturesCache.push(texture);
  14864. return texture;
  14865. };
  14866. /**
  14867. * Update the sampling mode of a given texture
  14868. * @param samplingMode defines the required sampling mode
  14869. * @param texture defines the texture to update
  14870. */
  14871. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14872. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14873. if (texture.isCube) {
  14874. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14875. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14876. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14877. }
  14878. else if (texture.is3D) {
  14879. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14880. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14881. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14882. }
  14883. else {
  14884. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14885. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14886. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14887. }
  14888. texture.samplingMode = samplingMode;
  14889. };
  14890. /**
  14891. * Update the content of a dynamic texture
  14892. * @param texture defines the texture to update
  14893. * @param canvas defines the canvas containing the source
  14894. * @param invertY defines if data must be stored with Y axis inverted
  14895. * @param premulAlpha defines if alpha is stored as premultiplied
  14896. * @param format defines the format of the data
  14897. */
  14898. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14899. if (premulAlpha === void 0) { premulAlpha = false; }
  14900. if (!texture) {
  14901. return;
  14902. }
  14903. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14904. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14905. if (premulAlpha) {
  14906. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14907. }
  14908. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14909. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14910. if (texture.generateMipMaps) {
  14911. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14912. }
  14913. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14914. if (premulAlpha) {
  14915. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14916. }
  14917. texture.isReady = true;
  14918. };
  14919. /**
  14920. * Update a video texture
  14921. * @param texture defines the texture to update
  14922. * @param video defines the video element to use
  14923. * @param invertY defines if data must be stored with Y axis inverted
  14924. */
  14925. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14926. if (!texture || texture._isDisabled) {
  14927. return;
  14928. }
  14929. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14930. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14931. try {
  14932. // Testing video texture support
  14933. if (this._videoTextureSupported === undefined) {
  14934. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14935. if (this._gl.getError() !== 0) {
  14936. this._videoTextureSupported = false;
  14937. }
  14938. else {
  14939. this._videoTextureSupported = true;
  14940. }
  14941. }
  14942. // Copy video through the current working canvas if video texture is not supported
  14943. if (!this._videoTextureSupported) {
  14944. if (!texture._workingCanvas) {
  14945. texture._workingCanvas = document.createElement("canvas");
  14946. var context = texture._workingCanvas.getContext("2d");
  14947. if (!context) {
  14948. throw new Error("Unable to get 2d context");
  14949. }
  14950. texture._workingContext = context;
  14951. texture._workingCanvas.width = texture.width;
  14952. texture._workingCanvas.height = texture.height;
  14953. }
  14954. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14955. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14956. }
  14957. else {
  14958. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14959. }
  14960. if (texture.generateMipMaps) {
  14961. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14962. }
  14963. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14964. // this.resetTextureCache();
  14965. texture.isReady = true;
  14966. }
  14967. catch (ex) {
  14968. // Something unexpected
  14969. // Let's disable the texture
  14970. texture._isDisabled = true;
  14971. }
  14972. };
  14973. /**
  14974. * Updates a depth texture Comparison Mode and Function.
  14975. * If the comparison Function is equal to 0, the mode will be set to none.
  14976. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14977. * @param texture The texture to set the comparison function for
  14978. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14979. */
  14980. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14981. if (this.webGLVersion === 1) {
  14982. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14983. return;
  14984. }
  14985. var gl = this._gl;
  14986. if (texture.isCube) {
  14987. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14988. if (comparisonFunction === 0) {
  14989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14991. }
  14992. else {
  14993. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14994. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14995. }
  14996. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14997. }
  14998. else {
  14999. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15000. if (comparisonFunction === 0) {
  15001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15003. }
  15004. else {
  15005. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15007. }
  15008. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15009. }
  15010. texture._comparisonFunction = comparisonFunction;
  15011. };
  15012. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15013. var width = size.width || size;
  15014. var height = size.height || size;
  15015. internalTexture.baseWidth = width;
  15016. internalTexture.baseHeight = height;
  15017. internalTexture.width = width;
  15018. internalTexture.height = height;
  15019. internalTexture.isReady = true;
  15020. internalTexture.samples = 1;
  15021. internalTexture.generateMipMaps = false;
  15022. internalTexture._generateDepthBuffer = true;
  15023. internalTexture._generateStencilBuffer = generateStencil;
  15024. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15025. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15026. internalTexture._comparisonFunction = comparisonFunction;
  15027. var gl = this._gl;
  15028. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15029. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15030. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15031. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15032. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15033. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15034. if (comparisonFunction === 0) {
  15035. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15036. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15037. }
  15038. else {
  15039. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15040. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15041. }
  15042. };
  15043. /**
  15044. * Creates a depth stencil texture.
  15045. * This is only available in WebGL 2 or with the depth texture extension available.
  15046. * @param size The size of face edge in the texture.
  15047. * @param options The options defining the texture.
  15048. * @returns The texture
  15049. */
  15050. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15051. if (options.isCube) {
  15052. var width = size.width || size;
  15053. return this._createDepthStencilCubeTexture(width, options);
  15054. }
  15055. else {
  15056. return this._createDepthStencilTexture(size, options);
  15057. }
  15058. };
  15059. /**
  15060. * Creates a depth stencil texture.
  15061. * This is only available in WebGL 2 or with the depth texture extension available.
  15062. * @param size The size of face edge in the texture.
  15063. * @param options The options defining the texture.
  15064. * @returns The texture
  15065. */
  15066. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15067. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15068. if (!this._caps.depthTextureExtension) {
  15069. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15070. return internalTexture;
  15071. }
  15072. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15073. var gl = this._gl;
  15074. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15075. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15076. if (this.webGLVersion > 1) {
  15077. if (internalOptions.generateStencil) {
  15078. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15079. }
  15080. else {
  15081. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15082. }
  15083. }
  15084. else {
  15085. if (internalOptions.generateStencil) {
  15086. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15087. }
  15088. else {
  15089. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15090. }
  15091. }
  15092. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15093. return internalTexture;
  15094. };
  15095. /**
  15096. * Creates a depth stencil cube texture.
  15097. * This is only available in WebGL 2.
  15098. * @param size The size of face edge in the cube texture.
  15099. * @param options The options defining the cube texture.
  15100. * @returns The cube texture
  15101. */
  15102. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15103. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15104. internalTexture.isCube = true;
  15105. if (this.webGLVersion === 1) {
  15106. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15107. return internalTexture;
  15108. }
  15109. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15110. var gl = this._gl;
  15111. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15112. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15113. // Create the depth/stencil buffer
  15114. for (var face = 0; face < 6; face++) {
  15115. if (internalOptions.generateStencil) {
  15116. 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);
  15117. }
  15118. else {
  15119. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15120. }
  15121. }
  15122. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15123. return internalTexture;
  15124. };
  15125. /**
  15126. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15127. * @param renderTarget The render target to set the frame buffer for
  15128. */
  15129. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15130. // Create the framebuffer
  15131. var internalTexture = renderTarget.getInternalTexture();
  15132. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15133. return;
  15134. }
  15135. var gl = this._gl;
  15136. var depthStencilTexture = renderTarget.depthStencilTexture;
  15137. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15138. if (depthStencilTexture.isCube) {
  15139. if (depthStencilTexture._generateStencilBuffer) {
  15140. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15141. }
  15142. else {
  15143. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15144. }
  15145. }
  15146. else {
  15147. if (depthStencilTexture._generateStencilBuffer) {
  15148. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15149. }
  15150. else {
  15151. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15152. }
  15153. }
  15154. this.bindUnboundFramebuffer(null);
  15155. };
  15156. /**
  15157. * Creates a new render target texture
  15158. * @param size defines the size of the texture
  15159. * @param options defines the options used to create the texture
  15160. * @returns a new render target texture stored in an InternalTexture
  15161. */
  15162. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15163. var fullOptions = new RenderTargetCreationOptions();
  15164. if (options !== undefined && typeof options === "object") {
  15165. fullOptions.generateMipMaps = options.generateMipMaps;
  15166. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15167. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15168. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15169. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15170. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15171. }
  15172. else {
  15173. fullOptions.generateMipMaps = options;
  15174. fullOptions.generateDepthBuffer = true;
  15175. fullOptions.generateStencilBuffer = false;
  15176. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15177. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15178. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15179. }
  15180. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15181. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15182. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15183. }
  15184. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15185. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15186. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15187. }
  15188. var gl = this._gl;
  15189. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15190. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15191. var width = size.width || size;
  15192. var height = size.height || size;
  15193. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15194. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15195. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15196. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15197. }
  15198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15202. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15203. // Create the framebuffer
  15204. var currentFrameBuffer = this._currentFramebuffer;
  15205. var framebuffer = gl.createFramebuffer();
  15206. this.bindUnboundFramebuffer(framebuffer);
  15207. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15208. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15209. if (fullOptions.generateMipMaps) {
  15210. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15211. }
  15212. // Unbind
  15213. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15214. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15215. this.bindUnboundFramebuffer(currentFrameBuffer);
  15216. texture._framebuffer = framebuffer;
  15217. texture.baseWidth = width;
  15218. texture.baseHeight = height;
  15219. texture.width = width;
  15220. texture.height = height;
  15221. texture.isReady = true;
  15222. texture.samples = 1;
  15223. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15224. texture.samplingMode = fullOptions.samplingMode;
  15225. texture.type = fullOptions.type;
  15226. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15227. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15228. // this.resetTextureCache();
  15229. this._internalTexturesCache.push(texture);
  15230. return texture;
  15231. };
  15232. /**
  15233. * Create a multi render target texture
  15234. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15235. * @param size defines the size of the texture
  15236. * @param options defines the creation options
  15237. * @returns the cube texture as an InternalTexture
  15238. */
  15239. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15240. var generateMipMaps = false;
  15241. var generateDepthBuffer = true;
  15242. var generateStencilBuffer = false;
  15243. var generateDepthTexture = false;
  15244. var textureCount = 1;
  15245. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15246. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15247. var types = new Array();
  15248. var samplingModes = new Array();
  15249. if (options !== undefined) {
  15250. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15251. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15252. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15253. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15254. textureCount = options.textureCount || 1;
  15255. if (options.types) {
  15256. types = options.types;
  15257. }
  15258. if (options.samplingModes) {
  15259. samplingModes = options.samplingModes;
  15260. }
  15261. }
  15262. var gl = this._gl;
  15263. // Create the framebuffer
  15264. var framebuffer = gl.createFramebuffer();
  15265. this.bindUnboundFramebuffer(framebuffer);
  15266. var width = size.width || size;
  15267. var height = size.height || size;
  15268. var textures = [];
  15269. var attachments = [];
  15270. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15271. for (var i = 0; i < textureCount; i++) {
  15272. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15273. var type = types[i] || defaultType;
  15274. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15275. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15276. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15277. }
  15278. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15279. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15280. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15281. }
  15282. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15283. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15284. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15285. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15286. }
  15287. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15288. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15289. textures.push(texture);
  15290. attachments.push(attachment);
  15291. gl.activeTexture(gl["TEXTURE" + i]);
  15292. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15293. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15297. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15298. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15299. if (generateMipMaps) {
  15300. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15301. }
  15302. // Unbind
  15303. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15304. texture._framebuffer = framebuffer;
  15305. texture._depthStencilBuffer = depthStencilBuffer;
  15306. texture.baseWidth = width;
  15307. texture.baseHeight = height;
  15308. texture.width = width;
  15309. texture.height = height;
  15310. texture.isReady = true;
  15311. texture.samples = 1;
  15312. texture.generateMipMaps = generateMipMaps;
  15313. texture.samplingMode = samplingMode;
  15314. texture.type = type;
  15315. texture._generateDepthBuffer = generateDepthBuffer;
  15316. texture._generateStencilBuffer = generateStencilBuffer;
  15317. texture._attachments = attachments;
  15318. this._internalTexturesCache.push(texture);
  15319. }
  15320. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15321. // Depth texture
  15322. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15323. gl.activeTexture(gl.TEXTURE0);
  15324. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15325. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15326. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15327. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15328. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15329. 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);
  15330. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15331. depthTexture._framebuffer = framebuffer;
  15332. depthTexture.baseWidth = width;
  15333. depthTexture.baseHeight = height;
  15334. depthTexture.width = width;
  15335. depthTexture.height = height;
  15336. depthTexture.isReady = true;
  15337. depthTexture.samples = 1;
  15338. depthTexture.generateMipMaps = generateMipMaps;
  15339. depthTexture.samplingMode = gl.NEAREST;
  15340. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15341. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15342. textures.push(depthTexture);
  15343. this._internalTexturesCache.push(depthTexture);
  15344. }
  15345. gl.drawBuffers(attachments);
  15346. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15347. this.bindUnboundFramebuffer(null);
  15348. this.resetTextureCache();
  15349. return textures;
  15350. };
  15351. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15352. if (samples === void 0) { samples = 1; }
  15353. var depthStencilBuffer = null;
  15354. var gl = this._gl;
  15355. // Create the depth/stencil buffer
  15356. if (generateStencilBuffer) {
  15357. depthStencilBuffer = gl.createRenderbuffer();
  15358. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15359. if (samples > 1) {
  15360. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15361. }
  15362. else {
  15363. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15364. }
  15365. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15366. }
  15367. else if (generateDepthBuffer) {
  15368. depthStencilBuffer = gl.createRenderbuffer();
  15369. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15370. if (samples > 1) {
  15371. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15372. }
  15373. else {
  15374. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15375. }
  15376. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15377. }
  15378. return depthStencilBuffer;
  15379. };
  15380. /**
  15381. * Updates the sample count of a render target texture
  15382. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15383. * @param texture defines the texture to update
  15384. * @param samples defines the sample count to set
  15385. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15386. */
  15387. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15388. if (this.webGLVersion < 2 || !texture) {
  15389. return 1;
  15390. }
  15391. if (texture.samples === samples) {
  15392. return samples;
  15393. }
  15394. var gl = this._gl;
  15395. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15396. // Dispose previous render buffers
  15397. if (texture._depthStencilBuffer) {
  15398. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15399. texture._depthStencilBuffer = null;
  15400. }
  15401. if (texture._MSAAFramebuffer) {
  15402. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15403. texture._MSAAFramebuffer = null;
  15404. }
  15405. if (texture._MSAARenderBuffer) {
  15406. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15407. texture._MSAARenderBuffer = null;
  15408. }
  15409. if (samples > 1) {
  15410. var framebuffer = gl.createFramebuffer();
  15411. if (!framebuffer) {
  15412. throw new Error("Unable to create multi sampled framebuffer");
  15413. }
  15414. texture._MSAAFramebuffer = framebuffer;
  15415. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15416. var colorRenderbuffer = gl.createRenderbuffer();
  15417. if (!colorRenderbuffer) {
  15418. throw new Error("Unable to create multi sampled framebuffer");
  15419. }
  15420. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15421. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15422. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15423. texture._MSAARenderBuffer = colorRenderbuffer;
  15424. }
  15425. else {
  15426. this.bindUnboundFramebuffer(texture._framebuffer);
  15427. }
  15428. texture.samples = samples;
  15429. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15430. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15431. this.bindUnboundFramebuffer(null);
  15432. return samples;
  15433. };
  15434. /**
  15435. * Update the sample count for a given multiple render target texture
  15436. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15437. * @param textures defines the textures to update
  15438. * @param samples defines the sample count to set
  15439. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15440. */
  15441. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15442. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15443. return 1;
  15444. }
  15445. if (textures[0].samples === samples) {
  15446. return samples;
  15447. }
  15448. var gl = this._gl;
  15449. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15450. // Dispose previous render buffers
  15451. if (textures[0]._depthStencilBuffer) {
  15452. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15453. textures[0]._depthStencilBuffer = null;
  15454. }
  15455. if (textures[0]._MSAAFramebuffer) {
  15456. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15457. textures[0]._MSAAFramebuffer = null;
  15458. }
  15459. for (var i = 0; i < textures.length; i++) {
  15460. if (textures[i]._MSAARenderBuffer) {
  15461. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15462. textures[i]._MSAARenderBuffer = null;
  15463. }
  15464. }
  15465. if (samples > 1) {
  15466. var framebuffer = gl.createFramebuffer();
  15467. if (!framebuffer) {
  15468. throw new Error("Unable to create multi sampled framebuffer");
  15469. }
  15470. this.bindUnboundFramebuffer(framebuffer);
  15471. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15472. var attachments = [];
  15473. for (var i = 0; i < textures.length; i++) {
  15474. var texture = textures[i];
  15475. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15476. var colorRenderbuffer = gl.createRenderbuffer();
  15477. if (!colorRenderbuffer) {
  15478. throw new Error("Unable to create multi sampled framebuffer");
  15479. }
  15480. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15481. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15482. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15483. texture._MSAAFramebuffer = framebuffer;
  15484. texture._MSAARenderBuffer = colorRenderbuffer;
  15485. texture.samples = samples;
  15486. texture._depthStencilBuffer = depthStencilBuffer;
  15487. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15488. attachments.push(attachment);
  15489. }
  15490. gl.drawBuffers(attachments);
  15491. }
  15492. else {
  15493. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15494. }
  15495. this.bindUnboundFramebuffer(null);
  15496. return samples;
  15497. };
  15498. /** @hidden */
  15499. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15500. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15501. };
  15502. /** @hidden */
  15503. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15504. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15505. };
  15506. /** @hidden */
  15507. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15508. var gl = this._gl;
  15509. var textureType = this._getWebGLTextureType(texture.type);
  15510. var format = this._getInternalFormat(texture.format);
  15511. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15512. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15513. this._bindTextureDirectly(bindTarget, texture, true);
  15514. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0);
  15515. var target = gl.TEXTURE_2D;
  15516. if (texture.isCube) {
  15517. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15518. }
  15519. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15520. this._bindTextureDirectly(bindTarget, null, true);
  15521. };
  15522. /**
  15523. * Creates a new render target cube texture
  15524. * @param size defines the size of the texture
  15525. * @param options defines the options used to create the texture
  15526. * @returns a new render target cube texture stored in an InternalTexture
  15527. */
  15528. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15529. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15530. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15531. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15532. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15533. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15534. }
  15535. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15536. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15537. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15538. }
  15539. var gl = this._gl;
  15540. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15541. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15542. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15543. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15544. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15545. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15546. }
  15547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15551. for (var face = 0; face < 6; face++) {
  15552. 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);
  15553. }
  15554. // Create the framebuffer
  15555. var framebuffer = gl.createFramebuffer();
  15556. this.bindUnboundFramebuffer(framebuffer);
  15557. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15558. // MipMaps
  15559. if (fullOptions.generateMipMaps) {
  15560. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15561. }
  15562. // Unbind
  15563. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15564. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15565. this.bindUnboundFramebuffer(null);
  15566. texture._framebuffer = framebuffer;
  15567. texture.width = size;
  15568. texture.height = size;
  15569. texture.isReady = true;
  15570. texture.isCube = true;
  15571. texture.samples = 1;
  15572. texture.generateMipMaps = fullOptions.generateMipMaps;
  15573. texture.samplingMode = fullOptions.samplingMode;
  15574. texture.type = fullOptions.type;
  15575. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15576. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15577. this._internalTexturesCache.push(texture);
  15578. return texture;
  15579. };
  15580. /**
  15581. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15582. * @param rootUrl defines the url where the file to load is located
  15583. * @param scene defines the current scene
  15584. * @param lodScale defines scale to apply to the mip map selection
  15585. * @param lodOffset defines offset to apply to the mip map selection
  15586. * @param onLoad defines an optional callback raised when the texture is loaded
  15587. * @param onError defines an optional callback raised if there is an issue to load the texture
  15588. * @param format defines the format of the data
  15589. * @param forcedExtension defines the extension to use to pick the right loader
  15590. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15591. * @returns the cube texture as an InternalTexture
  15592. */
  15593. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15594. var _this = this;
  15595. if (onLoad === void 0) { onLoad = null; }
  15596. if (onError === void 0) { onError = null; }
  15597. if (forcedExtension === void 0) { forcedExtension = null; }
  15598. if (createPolynomials === void 0) { createPolynomials = true; }
  15599. var callback = function (loadData) {
  15600. if (!loadData) {
  15601. if (onLoad) {
  15602. onLoad(null);
  15603. }
  15604. return;
  15605. }
  15606. var texture = loadData.texture;
  15607. if (!createPolynomials) {
  15608. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15609. }
  15610. else if (loadData.info.sphericalPolynomial) {
  15611. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15612. }
  15613. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15614. if (_this._caps.textureLOD) {
  15615. // Do not add extra process if texture lod is supported.
  15616. if (onLoad) {
  15617. onLoad(texture);
  15618. }
  15619. return;
  15620. }
  15621. var mipSlices = 3;
  15622. var gl = _this._gl;
  15623. var width = loadData.width;
  15624. if (!width) {
  15625. return;
  15626. }
  15627. var textures = [];
  15628. for (var i = 0; i < mipSlices; i++) {
  15629. //compute LOD from even spacing in smoothness (matching shader calculation)
  15630. var smoothness = i / (mipSlices - 1);
  15631. var roughness = 1 - smoothness;
  15632. var minLODIndex = lodOffset; // roughness = 0
  15633. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15634. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15635. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15636. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15637. glTextureFromLod.isCube = true;
  15638. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15640. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15641. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15643. if (loadData.isDDS) {
  15644. var info = loadData.info;
  15645. var data = loadData.data;
  15646. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15647. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15648. }
  15649. else {
  15650. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15651. }
  15652. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15653. // Wrap in a base texture for easy binding.
  15654. var lodTexture = new BABYLON.BaseTexture(scene);
  15655. lodTexture.isCube = true;
  15656. lodTexture._texture = glTextureFromLod;
  15657. glTextureFromLod.isReady = true;
  15658. textures.push(lodTexture);
  15659. }
  15660. texture._lodTextureHigh = textures[2];
  15661. texture._lodTextureMid = textures[1];
  15662. texture._lodTextureLow = textures[0];
  15663. if (onLoad) {
  15664. onLoad(texture);
  15665. }
  15666. };
  15667. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15668. };
  15669. /**
  15670. * Creates a cube texture
  15671. * @param rootUrl defines the url where the files to load is located
  15672. * @param scene defines the current scene
  15673. * @param files defines the list of files to load (1 per face)
  15674. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15675. * @param onLoad defines an optional callback raised when the texture is loaded
  15676. * @param onError defines an optional callback raised if there is an issue to load the texture
  15677. * @param format defines the format of the data
  15678. * @param forcedExtension defines the extension to use to pick the right loader
  15679. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15680. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15681. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15682. * @returns the cube texture as an InternalTexture
  15683. */
  15684. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15685. var _this = this;
  15686. if (onLoad === void 0) { onLoad = null; }
  15687. if (onError === void 0) { onError = null; }
  15688. if (forcedExtension === void 0) { forcedExtension = null; }
  15689. if (createPolynomials === void 0) { createPolynomials = false; }
  15690. if (lodScale === void 0) { lodScale = 0; }
  15691. if (lodOffset === void 0) { lodOffset = 0; }
  15692. var gl = this._gl;
  15693. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15694. texture.isCube = true;
  15695. texture.url = rootUrl;
  15696. texture.generateMipMaps = !noMipmap;
  15697. texture._lodGenerationScale = lodScale;
  15698. texture._lodGenerationOffset = lodOffset;
  15699. if (!this._doNotHandleContextLost) {
  15700. texture._extension = forcedExtension;
  15701. texture._files = files;
  15702. }
  15703. var isKTX = false;
  15704. var isDDS = false;
  15705. var isEnv = false;
  15706. var lastDot = rootUrl.lastIndexOf('.');
  15707. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15708. if (this._textureFormatInUse) {
  15709. extension = this._textureFormatInUse;
  15710. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15711. isKTX = true;
  15712. }
  15713. else {
  15714. isDDS = (extension === ".dds");
  15715. isEnv = (extension === ".env");
  15716. }
  15717. var onerror = function (request, exception) {
  15718. if (onError && request) {
  15719. onError(request.status + " " + request.statusText, exception);
  15720. }
  15721. };
  15722. if (isKTX) {
  15723. this._loadFile(rootUrl, function (data) {
  15724. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15725. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15726. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15727. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15728. ktx.uploadLevels(_this._gl, !noMipmap);
  15729. _this.setCubeMapTextureParams(gl, loadMipmap);
  15730. texture.width = ktx.pixelWidth;
  15731. texture.height = ktx.pixelHeight;
  15732. texture.isReady = true;
  15733. }, undefined, undefined, true, onerror);
  15734. }
  15735. else if (isEnv) {
  15736. this._loadFile(rootUrl, function (data) {
  15737. data = data;
  15738. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15739. if (info) {
  15740. texture.width = info.width;
  15741. texture.height = info.width;
  15742. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15743. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15744. texture.isReady = true;
  15745. if (onLoad) {
  15746. onLoad();
  15747. }
  15748. });
  15749. }
  15750. else if (onError) {
  15751. onError("Can not parse the environment file", null);
  15752. }
  15753. }, undefined, undefined, true, onerror);
  15754. }
  15755. else if (isDDS) {
  15756. if (files && files.length === 6) {
  15757. this._cascadeLoadFiles(scene, function (imgs) {
  15758. var info;
  15759. var loadMipmap = false;
  15760. var width = 0;
  15761. for (var index = 0; index < imgs.length; index++) {
  15762. var data = imgs[index];
  15763. info = BABYLON.DDSTools.GetDDSInfo(data);
  15764. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15765. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15766. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15767. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15768. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15769. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15770. }
  15771. texture.width = info.width;
  15772. texture.height = info.height;
  15773. texture.type = info.textureType;
  15774. width = info.width;
  15775. }
  15776. _this.setCubeMapTextureParams(gl, loadMipmap);
  15777. texture.isReady = true;
  15778. if (onLoad) {
  15779. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15780. }
  15781. }, files, onError);
  15782. }
  15783. else {
  15784. this._loadFile(rootUrl, function (data) {
  15785. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15786. if (createPolynomials) {
  15787. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15788. }
  15789. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15790. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15791. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15792. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15793. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15794. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15795. }
  15796. _this.setCubeMapTextureParams(gl, loadMipmap);
  15797. texture.width = info.width;
  15798. texture.height = info.height;
  15799. texture.isReady = true;
  15800. texture.type = info.textureType;
  15801. if (onLoad) {
  15802. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15803. }
  15804. }, undefined, undefined, true, onerror);
  15805. }
  15806. }
  15807. else {
  15808. if (!files) {
  15809. throw new Error("Cannot load cubemap because files were not defined");
  15810. }
  15811. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15812. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15813. var height = width;
  15814. _this._prepareWorkingCanvas();
  15815. if (!_this._workingCanvas || !_this._workingContext) {
  15816. return;
  15817. }
  15818. _this._workingCanvas.width = width;
  15819. _this._workingCanvas.height = height;
  15820. var faces = [
  15821. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15822. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15823. ];
  15824. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15825. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15826. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15827. for (var index = 0; index < faces.length; index++) {
  15828. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15829. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15830. }
  15831. if (!noMipmap) {
  15832. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15833. }
  15834. _this.setCubeMapTextureParams(gl, !noMipmap);
  15835. texture.width = width;
  15836. texture.height = height;
  15837. texture.isReady = true;
  15838. if (format) {
  15839. texture.format = format;
  15840. }
  15841. texture.onLoadedObservable.notifyObservers(texture);
  15842. texture.onLoadedObservable.clear();
  15843. if (onLoad) {
  15844. onLoad();
  15845. }
  15846. }, files, onError);
  15847. }
  15848. this._internalTexturesCache.push(texture);
  15849. return texture;
  15850. };
  15851. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15856. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15857. // this.resetTextureCache();
  15858. };
  15859. /**
  15860. * Update a raw cube texture
  15861. * @param texture defines the texture to udpdate
  15862. * @param data defines the data to store
  15863. * @param format defines the data format
  15864. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15865. * @param invertY defines if data must be stored with Y axis inverted
  15866. * @param compression defines the compression used (null by default)
  15867. * @param level defines which level of the texture to update
  15868. */
  15869. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15870. if (compression === void 0) { compression = null; }
  15871. if (level === void 0) { level = 0; }
  15872. texture._bufferViewArray = data;
  15873. texture.format = format;
  15874. texture.type = type;
  15875. texture.invertY = invertY;
  15876. texture._compression = compression;
  15877. var gl = this._gl;
  15878. var textureType = this._getWebGLTextureType(type);
  15879. var internalFormat = this._getInternalFormat(format);
  15880. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15881. var needConversion = false;
  15882. if (internalFormat === gl.RGB) {
  15883. internalFormat = gl.RGBA;
  15884. needConversion = true;
  15885. }
  15886. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15887. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15888. if (texture.width % 4 !== 0) {
  15889. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15890. }
  15891. // Data are known to be in +X +Y +Z -X -Y -Z
  15892. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15893. var faceData = data[faceIndex];
  15894. if (compression) {
  15895. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15896. }
  15897. else {
  15898. if (needConversion) {
  15899. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15900. }
  15901. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15902. }
  15903. }
  15904. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15905. if (isPot && texture.generateMipMaps && level === 0) {
  15906. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15907. }
  15908. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15909. // this.resetTextureCache();
  15910. texture.isReady = true;
  15911. };
  15912. /**
  15913. * Creates a new raw cube texture
  15914. * @param data defines the array of data to use to create each face
  15915. * @param size defines the size of the textures
  15916. * @param format defines the format of the data
  15917. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15918. * @param generateMipMaps defines if the engine should generate the mip levels
  15919. * @param invertY defines if data must be stored with Y axis inverted
  15920. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15921. * @param compression defines the compression used (null by default)
  15922. * @returns the cube texture as an InternalTexture
  15923. */
  15924. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15925. if (compression === void 0) { compression = null; }
  15926. var gl = this._gl;
  15927. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15928. texture.isCube = true;
  15929. texture.generateMipMaps = generateMipMaps;
  15930. texture.format = format;
  15931. texture.type = type;
  15932. if (!this._doNotHandleContextLost) {
  15933. texture._bufferViewArray = data;
  15934. }
  15935. var textureType = this._getWebGLTextureType(type);
  15936. var internalFormat = this._getInternalFormat(format);
  15937. if (internalFormat === gl.RGB) {
  15938. internalFormat = gl.RGBA;
  15939. }
  15940. var width = size;
  15941. var height = width;
  15942. texture.width = width;
  15943. texture.height = height;
  15944. // Double check on POT to generate Mips.
  15945. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15946. if (!isPot) {
  15947. generateMipMaps = false;
  15948. }
  15949. // Upload data if needed. The texture won't be ready until then.
  15950. if (data) {
  15951. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15952. }
  15953. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15954. // Filters
  15955. if (data && generateMipMaps) {
  15956. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15957. }
  15958. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15961. }
  15962. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15965. }
  15966. else {
  15967. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15968. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15969. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15970. }
  15971. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15972. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15973. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15974. return texture;
  15975. };
  15976. /**
  15977. * Creates a new raw cube texture from a specified url
  15978. * @param url defines the url where the data is located
  15979. * @param scene defines the current scene
  15980. * @param size defines the size of the textures
  15981. * @param format defines the format of the data
  15982. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15983. * @param noMipmap defines if the engine should avoid generating the mip levels
  15984. * @param callback defines a callback used to extract texture data from loaded data
  15985. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15986. * @param onLoad defines a callback called when texture is loaded
  15987. * @param onError defines a callback called if there is an error
  15988. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15989. * @param invertY defines if data must be stored with Y axis inverted
  15990. * @returns the cube texture as an InternalTexture
  15991. */
  15992. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15993. var _this = this;
  15994. if (onLoad === void 0) { onLoad = null; }
  15995. if (onError === void 0) { onError = null; }
  15996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15997. if (invertY === void 0) { invertY = false; }
  15998. var gl = this._gl;
  15999. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16000. scene._addPendingData(texture);
  16001. texture.url = url;
  16002. this._internalTexturesCache.push(texture);
  16003. var onerror = function (request, exception) {
  16004. scene._removePendingData(texture);
  16005. if (onError && request) {
  16006. onError(request.status + " " + request.statusText, exception);
  16007. }
  16008. };
  16009. var internalCallback = function (data) {
  16010. var width = texture.width;
  16011. var faceDataArrays = callback(data);
  16012. if (!faceDataArrays) {
  16013. return;
  16014. }
  16015. if (mipmapGenerator) {
  16016. var textureType = _this._getWebGLTextureType(type);
  16017. var internalFormat = _this._getInternalFormat(format);
  16018. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16019. var needConversion = false;
  16020. if (internalFormat === gl.RGB) {
  16021. internalFormat = gl.RGBA;
  16022. needConversion = true;
  16023. }
  16024. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16025. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16026. var mipData = mipmapGenerator(faceDataArrays);
  16027. for (var level = 0; level < mipData.length; level++) {
  16028. var mipSize = width >> level;
  16029. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16030. var mipFaceData = mipData[level][faceIndex];
  16031. if (needConversion) {
  16032. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16033. }
  16034. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16035. }
  16036. }
  16037. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16038. }
  16039. else {
  16040. texture.generateMipMaps = !noMipmap;
  16041. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16042. }
  16043. texture.isReady = true;
  16044. // this.resetTextureCache();
  16045. scene._removePendingData(texture);
  16046. if (onLoad) {
  16047. onLoad();
  16048. }
  16049. };
  16050. this._loadFile(url, function (data) {
  16051. internalCallback(data);
  16052. }, undefined, scene.database, true, onerror);
  16053. return texture;
  16054. };
  16055. ;
  16056. /**
  16057. * Update a raw 3D texture
  16058. * @param texture defines the texture to update
  16059. * @param data defines the data to store
  16060. * @param format defines the data format
  16061. * @param invertY defines if data must be stored with Y axis inverted
  16062. * @param compression defines the used compression (can be null)
  16063. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16064. */
  16065. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16066. if (compression === void 0) { compression = null; }
  16067. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16068. var internalType = this._getWebGLTextureType(textureType);
  16069. var internalFormat = this._getInternalFormat(format);
  16070. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16071. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16072. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16073. if (!this._doNotHandleContextLost) {
  16074. texture._bufferView = data;
  16075. texture.format = format;
  16076. texture.invertY = invertY;
  16077. texture._compression = compression;
  16078. }
  16079. if (texture.width % 4 !== 0) {
  16080. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16081. }
  16082. if (compression && data) {
  16083. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16084. }
  16085. else {
  16086. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16087. }
  16088. if (texture.generateMipMaps) {
  16089. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16090. }
  16091. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16092. // this.resetTextureCache();
  16093. texture.isReady = true;
  16094. };
  16095. /**
  16096. * Creates a new raw 3D texture
  16097. * @param data defines the data used to create the texture
  16098. * @param width defines the width of the texture
  16099. * @param height defines the height of the texture
  16100. * @param depth defines the depth of the texture
  16101. * @param format defines the format of the texture
  16102. * @param generateMipMaps defines if the engine must generate mip levels
  16103. * @param invertY defines if data must be stored with Y axis inverted
  16104. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16105. * @param compression defines the compressed used (can be null)
  16106. * @param textureType defines the compressed used (can be null)
  16107. * @returns a new raw 3D texture (stored in an InternalTexture)
  16108. */
  16109. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16110. if (compression === void 0) { compression = null; }
  16111. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16112. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16113. texture.baseWidth = width;
  16114. texture.baseHeight = height;
  16115. texture.baseDepth = depth;
  16116. texture.width = width;
  16117. texture.height = height;
  16118. texture.depth = depth;
  16119. texture.format = format;
  16120. texture.type = textureType;
  16121. texture.generateMipMaps = generateMipMaps;
  16122. texture.samplingMode = samplingMode;
  16123. texture.is3D = true;
  16124. if (!this._doNotHandleContextLost) {
  16125. texture._bufferView = data;
  16126. }
  16127. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16128. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16129. // Filters
  16130. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16131. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16132. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16133. if (generateMipMaps) {
  16134. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16135. }
  16136. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16137. this._internalTexturesCache.push(texture);
  16138. return texture;
  16139. };
  16140. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16141. var gl = this._gl;
  16142. if (!gl) {
  16143. return;
  16144. }
  16145. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16146. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16148. if (!noMipmap && !isCompressed) {
  16149. gl.generateMipmap(gl.TEXTURE_2D);
  16150. }
  16151. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16152. // this.resetTextureCache();
  16153. if (scene) {
  16154. scene._removePendingData(texture);
  16155. }
  16156. texture.onLoadedObservable.notifyObservers(texture);
  16157. texture.onLoadedObservable.clear();
  16158. };
  16159. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16160. var _this = this;
  16161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16162. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16163. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16164. var gl = this._gl;
  16165. if (!gl) {
  16166. return;
  16167. }
  16168. if (!texture._webGLTexture) {
  16169. // this.resetTextureCache();
  16170. if (scene) {
  16171. scene._removePendingData(texture);
  16172. }
  16173. return;
  16174. }
  16175. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16176. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16177. texture.baseWidth = width;
  16178. texture.baseHeight = height;
  16179. texture.width = potWidth;
  16180. texture.height = potHeight;
  16181. texture.isReady = true;
  16182. if (processFunction(potWidth, potHeight, function () {
  16183. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16184. })) {
  16185. // Returning as texture needs extra async steps
  16186. return;
  16187. }
  16188. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16189. };
  16190. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16191. // Create new RGBA data container.
  16192. var rgbaData;
  16193. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16194. rgbaData = new Float32Array(width * height * 4);
  16195. }
  16196. else {
  16197. rgbaData = new Uint32Array(width * height * 4);
  16198. }
  16199. // Convert each pixel.
  16200. for (var x = 0; x < width; x++) {
  16201. for (var y = 0; y < height; y++) {
  16202. var index = (y * width + x) * 3;
  16203. var newIndex = (y * width + x) * 4;
  16204. // Map Old Value to new value.
  16205. rgbaData[newIndex + 0] = rgbData[index + 0];
  16206. rgbaData[newIndex + 1] = rgbData[index + 1];
  16207. rgbaData[newIndex + 2] = rgbData[index + 2];
  16208. // Add fully opaque alpha channel.
  16209. rgbaData[newIndex + 3] = 1;
  16210. }
  16211. }
  16212. return rgbaData;
  16213. };
  16214. /** @hidden */
  16215. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16216. var gl = this._gl;
  16217. if (texture._framebuffer) {
  16218. gl.deleteFramebuffer(texture._framebuffer);
  16219. texture._framebuffer = null;
  16220. }
  16221. if (texture._depthStencilBuffer) {
  16222. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16223. texture._depthStencilBuffer = null;
  16224. }
  16225. if (texture._MSAAFramebuffer) {
  16226. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16227. texture._MSAAFramebuffer = null;
  16228. }
  16229. if (texture._MSAARenderBuffer) {
  16230. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16231. texture._MSAARenderBuffer = null;
  16232. }
  16233. };
  16234. /** @hidden */
  16235. Engine.prototype._releaseTexture = function (texture) {
  16236. var gl = this._gl;
  16237. this._releaseFramebufferObjects(texture);
  16238. gl.deleteTexture(texture._webGLTexture);
  16239. // Unbind channels
  16240. this.unbindAllTextures();
  16241. var index = this._internalTexturesCache.indexOf(texture);
  16242. if (index !== -1) {
  16243. this._internalTexturesCache.splice(index, 1);
  16244. }
  16245. // Integrated fixed lod samplers.
  16246. if (texture._lodTextureHigh) {
  16247. texture._lodTextureHigh.dispose();
  16248. }
  16249. if (texture._lodTextureMid) {
  16250. texture._lodTextureMid.dispose();
  16251. }
  16252. if (texture._lodTextureLow) {
  16253. texture._lodTextureLow.dispose();
  16254. }
  16255. // Set output texture of post process to null if the texture has been released/disposed
  16256. this.scenes.forEach(function (scene) {
  16257. scene.postProcesses.forEach(function (postProcess) {
  16258. if (postProcess._outputTexture == texture) {
  16259. postProcess._outputTexture = null;
  16260. }
  16261. });
  16262. scene.cameras.forEach(function (camera) {
  16263. camera._postProcesses.forEach(function (postProcess) {
  16264. if (postProcess) {
  16265. if (postProcess._outputTexture == texture) {
  16266. postProcess._outputTexture = null;
  16267. }
  16268. }
  16269. });
  16270. });
  16271. });
  16272. };
  16273. Engine.prototype.setProgram = function (program) {
  16274. if (this._currentProgram !== program) {
  16275. this._gl.useProgram(program);
  16276. this._currentProgram = program;
  16277. }
  16278. };
  16279. /**
  16280. * Binds an effect to the webGL context
  16281. * @param effect defines the effect to bind
  16282. */
  16283. Engine.prototype.bindSamplers = function (effect) {
  16284. this.setProgram(effect.getProgram());
  16285. var samplers = effect.getSamplers();
  16286. for (var index = 0; index < samplers.length; index++) {
  16287. var uniform = effect.getUniform(samplers[index]);
  16288. if (uniform) {
  16289. this._boundUniforms[index] = uniform;
  16290. }
  16291. }
  16292. this._currentEffect = null;
  16293. };
  16294. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16295. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16296. return;
  16297. }
  16298. // Remove
  16299. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16300. // Bind last to it
  16301. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16302. // Bind to dummy
  16303. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16304. };
  16305. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16306. if (!internalTexture) {
  16307. return -1;
  16308. }
  16309. internalTexture._initialSlot = channel;
  16310. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16311. if (channel !== internalTexture._designatedSlot) {
  16312. this._textureCollisions.addCount(1, false);
  16313. }
  16314. }
  16315. else {
  16316. if (channel !== internalTexture._designatedSlot) {
  16317. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16318. return internalTexture._designatedSlot;
  16319. }
  16320. else {
  16321. // No slot for this texture, let's pick a new one (if we find a free slot)
  16322. if (this._nextFreeTextureSlots.length) {
  16323. return this._nextFreeTextureSlots[0];
  16324. }
  16325. // We need to recycle the oldest bound texture, sorry.
  16326. this._textureCollisions.addCount(1, false);
  16327. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16328. }
  16329. }
  16330. }
  16331. return channel;
  16332. };
  16333. Engine.prototype._linkTrackers = function (previous, next) {
  16334. previous.next = next;
  16335. next.previous = previous;
  16336. };
  16337. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16338. var currentSlot = internalTexture._designatedSlot;
  16339. if (currentSlot === -1) {
  16340. return -1;
  16341. }
  16342. internalTexture._designatedSlot = -1;
  16343. if (this.disableTextureBindingOptimization) {
  16344. return -1;
  16345. }
  16346. // Remove from bound list
  16347. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16348. // Free the slot
  16349. this._boundTexturesCache[currentSlot] = null;
  16350. this._nextFreeTextureSlots.push(currentSlot);
  16351. return currentSlot;
  16352. };
  16353. Engine.prototype._activateCurrentTexture = function () {
  16354. if (this._currentTextureChannel !== this._activeChannel) {
  16355. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16356. this._currentTextureChannel = this._activeChannel;
  16357. }
  16358. };
  16359. /** @hidden */
  16360. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16361. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16362. if (force === void 0) { force = false; }
  16363. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16364. this._activeChannel = texture._designatedSlot;
  16365. }
  16366. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16367. var isTextureForRendering = texture && texture._initialSlot > -1;
  16368. if (currentTextureBound !== texture || force) {
  16369. if (currentTextureBound) {
  16370. this._removeDesignatedSlot(currentTextureBound);
  16371. }
  16372. this._activateCurrentTexture();
  16373. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16374. this._boundTexturesCache[this._activeChannel] = texture;
  16375. if (texture) {
  16376. if (!this.disableTextureBindingOptimization) {
  16377. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16378. if (slotIndex > -1) {
  16379. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16380. }
  16381. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16382. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16383. }
  16384. texture._designatedSlot = this._activeChannel;
  16385. }
  16386. }
  16387. else if (forTextureDataUpdate) {
  16388. this._activateCurrentTexture();
  16389. }
  16390. if (isTextureForRendering && !forTextureDataUpdate) {
  16391. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16392. }
  16393. };
  16394. /** @hidden */
  16395. Engine.prototype._bindTexture = function (channel, texture) {
  16396. if (channel < 0) {
  16397. return;
  16398. }
  16399. if (texture) {
  16400. channel = this._getCorrectTextureChannel(channel, texture);
  16401. }
  16402. this._activeChannel = channel;
  16403. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16404. };
  16405. /**
  16406. * Sets a texture to the webGL context from a postprocess
  16407. * @param channel defines the channel to use
  16408. * @param postProcess defines the source postprocess
  16409. */
  16410. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16411. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16412. };
  16413. /**
  16414. * Binds the output of the passed in post process to the texture channel specified
  16415. * @param channel The channel the texture should be bound to
  16416. * @param postProcess The post process which's output should be bound
  16417. */
  16418. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16419. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16420. };
  16421. /**
  16422. * Unbind all textures from the webGL context
  16423. */
  16424. Engine.prototype.unbindAllTextures = function () {
  16425. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16426. this._activeChannel = channel;
  16427. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16428. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16429. if (this.webGLVersion > 1) {
  16430. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16431. }
  16432. }
  16433. };
  16434. /**
  16435. * Sets a texture to the according uniform.
  16436. * @param channel The texture channel
  16437. * @param uniform The uniform to set
  16438. * @param texture The texture to apply
  16439. */
  16440. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16441. if (channel < 0) {
  16442. return;
  16443. }
  16444. if (uniform) {
  16445. this._boundUniforms[channel] = uniform;
  16446. }
  16447. this._setTexture(channel, texture);
  16448. };
  16449. /**
  16450. * Sets a depth stencil texture from a render target to the according uniform.
  16451. * @param channel The texture channel
  16452. * @param uniform The uniform to set
  16453. * @param texture The render target texture containing the depth stencil texture to apply
  16454. */
  16455. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16456. if (channel < 0) {
  16457. return;
  16458. }
  16459. if (uniform) {
  16460. this._boundUniforms[channel] = uniform;
  16461. }
  16462. if (!texture || !texture.depthStencilTexture) {
  16463. this._setTexture(channel, null);
  16464. }
  16465. else {
  16466. this._setTexture(channel, texture, false, true);
  16467. }
  16468. };
  16469. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16470. var uniform = this._boundUniforms[sourceSlot];
  16471. if (uniform._currentState === destination) {
  16472. return;
  16473. }
  16474. this._gl.uniform1i(uniform, destination);
  16475. uniform._currentState = destination;
  16476. };
  16477. Engine.prototype._getTextureWrapMode = function (mode) {
  16478. switch (mode) {
  16479. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16480. return this._gl.REPEAT;
  16481. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16482. return this._gl.CLAMP_TO_EDGE;
  16483. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16484. return this._gl.MIRRORED_REPEAT;
  16485. }
  16486. return this._gl.REPEAT;
  16487. };
  16488. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16489. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16490. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16491. // Not ready?
  16492. if (!texture) {
  16493. if (this._boundTexturesCache[channel] != null) {
  16494. this._activeChannel = channel;
  16495. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16496. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16497. if (this.webGLVersion > 1) {
  16498. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16499. }
  16500. }
  16501. return false;
  16502. }
  16503. // Video
  16504. if (texture.video) {
  16505. this._activeChannel = channel;
  16506. texture.update();
  16507. }
  16508. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16509. texture.delayLoad();
  16510. return false;
  16511. }
  16512. var internalTexture;
  16513. if (depthStencilTexture) {
  16514. internalTexture = texture.depthStencilTexture;
  16515. }
  16516. else if (texture.isReady()) {
  16517. internalTexture = texture.getInternalTexture();
  16518. }
  16519. else if (texture.isCube) {
  16520. internalTexture = this.emptyCubeTexture;
  16521. }
  16522. else if (texture.is3D) {
  16523. internalTexture = this.emptyTexture3D;
  16524. }
  16525. else {
  16526. internalTexture = this.emptyTexture;
  16527. }
  16528. if (!isPartOfTextureArray) {
  16529. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16530. }
  16531. var needToBind = true;
  16532. if (this._boundTexturesCache[channel] === internalTexture) {
  16533. this._moveBoundTextureOnTop(internalTexture);
  16534. if (!isPartOfTextureArray) {
  16535. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16536. }
  16537. needToBind = false;
  16538. }
  16539. this._activeChannel = channel;
  16540. if (internalTexture && internalTexture.is3D) {
  16541. if (needToBind) {
  16542. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16543. }
  16544. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16545. internalTexture._cachedWrapU = texture.wrapU;
  16546. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16547. }
  16548. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16549. internalTexture._cachedWrapV = texture.wrapV;
  16550. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16551. }
  16552. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16553. internalTexture._cachedWrapR = texture.wrapR;
  16554. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16555. }
  16556. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16557. }
  16558. else if (internalTexture && internalTexture.isCube) {
  16559. if (needToBind) {
  16560. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16561. }
  16562. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16563. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16564. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16565. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16566. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16567. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16568. }
  16569. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16570. }
  16571. else {
  16572. if (needToBind) {
  16573. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16574. }
  16575. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16576. internalTexture._cachedWrapU = texture.wrapU;
  16577. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16578. }
  16579. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16580. internalTexture._cachedWrapV = texture.wrapV;
  16581. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16582. }
  16583. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16584. }
  16585. return true;
  16586. };
  16587. /**
  16588. * Sets an array of texture to the webGL context
  16589. * @param channel defines the channel where the texture array must be set
  16590. * @param uniform defines the associated uniform location
  16591. * @param textures defines the array of textures to bind
  16592. */
  16593. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16594. if (channel < 0 || !uniform) {
  16595. return;
  16596. }
  16597. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16598. this._textureUnits = new Int32Array(textures.length);
  16599. }
  16600. for (var i = 0; i < textures.length; i++) {
  16601. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16602. }
  16603. this._gl.uniform1iv(uniform, this._textureUnits);
  16604. for (var index = 0; index < textures.length; index++) {
  16605. this._setTexture(this._textureUnits[index], textures[index], true);
  16606. }
  16607. };
  16608. /** @hidden */
  16609. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16610. var internalTexture = texture.getInternalTexture();
  16611. if (!internalTexture) {
  16612. return;
  16613. }
  16614. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16615. var value = texture.anisotropicFilteringLevel;
  16616. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16617. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16618. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16619. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16620. }
  16621. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16622. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16623. internalTexture._cachedAnisotropicFilteringLevel = value;
  16624. }
  16625. };
  16626. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16627. this._bindTextureDirectly(target, texture, true, true);
  16628. this._gl.texParameterf(target, parameter, value);
  16629. };
  16630. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16631. if (texture) {
  16632. this._bindTextureDirectly(target, texture, true, true);
  16633. }
  16634. this._gl.texParameteri(target, parameter, value);
  16635. };
  16636. /**
  16637. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16638. * @param x defines the x coordinate of the rectangle where pixels must be read
  16639. * @param y defines the y coordinate of the rectangle where pixels must be read
  16640. * @param width defines the width of the rectangle where pixels must be read
  16641. * @param height defines the height of the rectangle where pixels must be read
  16642. * @returns a Uint8Array containing RGBA colors
  16643. */
  16644. Engine.prototype.readPixels = function (x, y, width, height) {
  16645. var data = new Uint8Array(height * width * 4);
  16646. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16647. return data;
  16648. };
  16649. /**
  16650. * Add an externaly attached data from its key.
  16651. * This method call will fail and return false, if such key already exists.
  16652. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16653. * @param key the unique key that identifies the data
  16654. * @param data the data object to associate to the key for this Engine instance
  16655. * @return true if no such key were already present and the data was added successfully, false otherwise
  16656. */
  16657. Engine.prototype.addExternalData = function (key, data) {
  16658. if (!this._externalData) {
  16659. this._externalData = new BABYLON.StringDictionary();
  16660. }
  16661. return this._externalData.add(key, data);
  16662. };
  16663. /**
  16664. * Get an externaly attached data from its key
  16665. * @param key the unique key that identifies the data
  16666. * @return the associated data, if present (can be null), or undefined if not present
  16667. */
  16668. Engine.prototype.getExternalData = function (key) {
  16669. if (!this._externalData) {
  16670. this._externalData = new BABYLON.StringDictionary();
  16671. }
  16672. return this._externalData.get(key);
  16673. };
  16674. /**
  16675. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16676. * @param key the unique key that identifies the data
  16677. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16678. * @return the associated data, can be null if the factory returned null.
  16679. */
  16680. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16681. if (!this._externalData) {
  16682. this._externalData = new BABYLON.StringDictionary();
  16683. }
  16684. return this._externalData.getOrAddWithFactory(key, factory);
  16685. };
  16686. /**
  16687. * Remove an externaly attached data from the Engine instance
  16688. * @param key the unique key that identifies the data
  16689. * @return true if the data was successfully removed, false if it doesn't exist
  16690. */
  16691. Engine.prototype.removeExternalData = function (key) {
  16692. if (!this._externalData) {
  16693. this._externalData = new BABYLON.StringDictionary();
  16694. }
  16695. return this._externalData.remove(key);
  16696. };
  16697. /**
  16698. * Unbind all vertex attributes from the webGL context
  16699. */
  16700. Engine.prototype.unbindAllAttributes = function () {
  16701. if (this._mustWipeVertexAttributes) {
  16702. this._mustWipeVertexAttributes = false;
  16703. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16704. this._gl.disableVertexAttribArray(i);
  16705. this._vertexAttribArraysEnabled[i] = false;
  16706. this._currentBufferPointers[i].active = false;
  16707. }
  16708. return;
  16709. }
  16710. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16711. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16712. continue;
  16713. }
  16714. this._gl.disableVertexAttribArray(i);
  16715. this._vertexAttribArraysEnabled[i] = false;
  16716. this._currentBufferPointers[i].active = false;
  16717. }
  16718. };
  16719. /**
  16720. * 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
  16721. */
  16722. Engine.prototype.releaseEffects = function () {
  16723. for (var name in this._compiledEffects) {
  16724. this._deleteProgram(this._compiledEffects[name]._program);
  16725. }
  16726. this._compiledEffects = {};
  16727. };
  16728. /**
  16729. * Dispose and release all associated resources
  16730. */
  16731. Engine.prototype.dispose = function () {
  16732. this.hideLoadingUI();
  16733. this.stopRenderLoop();
  16734. // Release postProcesses
  16735. while (this.postProcesses.length) {
  16736. this.postProcesses[0].dispose();
  16737. }
  16738. // Empty texture
  16739. if (this._emptyTexture) {
  16740. this._releaseTexture(this._emptyTexture);
  16741. this._emptyTexture = null;
  16742. }
  16743. if (this._emptyCubeTexture) {
  16744. this._releaseTexture(this._emptyCubeTexture);
  16745. this._emptyCubeTexture = null;
  16746. }
  16747. // Rescale PP
  16748. if (this._rescalePostProcess) {
  16749. this._rescalePostProcess.dispose();
  16750. }
  16751. // Release scenes
  16752. while (this.scenes.length) {
  16753. this.scenes[0].dispose();
  16754. }
  16755. // Release audio engine
  16756. if (Engine.audioEngine) {
  16757. Engine.audioEngine.dispose();
  16758. }
  16759. // Release effects
  16760. this.releaseEffects();
  16761. // Unbind
  16762. this.unbindAllAttributes();
  16763. this._boundUniforms = [];
  16764. if (this._dummyFramebuffer) {
  16765. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16766. }
  16767. //WebVR
  16768. this.disableVR();
  16769. // Events
  16770. if (BABYLON.Tools.IsWindowObjectExist()) {
  16771. window.removeEventListener("blur", this._onBlur);
  16772. window.removeEventListener("focus", this._onFocus);
  16773. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16774. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16775. if (this._renderingCanvas) {
  16776. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16777. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16778. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16779. if (!this._doNotHandleContextLost) {
  16780. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16781. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16782. }
  16783. }
  16784. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16785. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16786. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16787. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16788. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16789. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16790. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16791. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16792. if (this._onVrDisplayConnect) {
  16793. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16794. if (this._onVrDisplayDisconnect) {
  16795. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16796. }
  16797. if (this._onVrDisplayPresentChange) {
  16798. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16799. }
  16800. this._onVrDisplayConnect = null;
  16801. this._onVrDisplayDisconnect = null;
  16802. }
  16803. }
  16804. // Remove from Instances
  16805. var index = Engine.Instances.indexOf(this);
  16806. if (index >= 0) {
  16807. Engine.Instances.splice(index, 1);
  16808. }
  16809. this._workingCanvas = null;
  16810. this._workingContext = null;
  16811. this._currentBufferPointers = [];
  16812. this._renderingCanvas = null;
  16813. this._currentProgram = null;
  16814. this._bindedRenderFunction = null;
  16815. this.onResizeObservable.clear();
  16816. this.onCanvasBlurObservable.clear();
  16817. this.onCanvasFocusObservable.clear();
  16818. this.onCanvasPointerOutObservable.clear();
  16819. this.onBeginFrameObservable.clear();
  16820. this.onEndFrameObservable.clear();
  16821. BABYLON.Effect.ResetCache();
  16822. // Abort active requests
  16823. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16824. var request = _a[_i];
  16825. request.abort();
  16826. }
  16827. };
  16828. // Loading screen
  16829. /**
  16830. * Display the loading screen
  16831. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16832. */
  16833. Engine.prototype.displayLoadingUI = function () {
  16834. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16835. return;
  16836. }
  16837. var loadingScreen = this.loadingScreen;
  16838. if (loadingScreen) {
  16839. loadingScreen.displayLoadingUI();
  16840. }
  16841. };
  16842. /**
  16843. * Hide the loading screen
  16844. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16845. */
  16846. Engine.prototype.hideLoadingUI = function () {
  16847. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16848. return;
  16849. }
  16850. var loadingScreen = this.loadingScreen;
  16851. if (loadingScreen) {
  16852. loadingScreen.hideLoadingUI();
  16853. }
  16854. };
  16855. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16856. /**
  16857. * Gets the current loading screen object
  16858. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16859. */
  16860. get: function () {
  16861. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16862. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16863. return this._loadingScreen;
  16864. },
  16865. /**
  16866. * Sets the current loading screen object
  16867. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16868. */
  16869. set: function (loadingScreen) {
  16870. this._loadingScreen = loadingScreen;
  16871. },
  16872. enumerable: true,
  16873. configurable: true
  16874. });
  16875. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16876. /**
  16877. * Sets the current loading screen text
  16878. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16879. */
  16880. set: function (text) {
  16881. this.loadingScreen.loadingUIText = text;
  16882. },
  16883. enumerable: true,
  16884. configurable: true
  16885. });
  16886. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16887. /**
  16888. * Sets the current loading screen background color
  16889. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16890. */
  16891. set: function (color) {
  16892. this.loadingScreen.loadingUIBackgroundColor = color;
  16893. },
  16894. enumerable: true,
  16895. configurable: true
  16896. });
  16897. /**
  16898. * Attach a new callback raised when context lost event is fired
  16899. * @param callback defines the callback to call
  16900. */
  16901. Engine.prototype.attachContextLostEvent = function (callback) {
  16902. if (this._renderingCanvas) {
  16903. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16904. }
  16905. };
  16906. /**
  16907. * Attach a new callback raised when context restored event is fired
  16908. * @param callback defines the callback to call
  16909. */
  16910. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16911. if (this._renderingCanvas) {
  16912. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16913. }
  16914. };
  16915. /**
  16916. * Gets the source code of the vertex shader associated with a specific webGL program
  16917. * @param program defines the program to use
  16918. * @returns a string containing the source code of the vertex shader associated with the program
  16919. */
  16920. Engine.prototype.getVertexShaderSource = function (program) {
  16921. var shaders = this._gl.getAttachedShaders(program);
  16922. if (!shaders) {
  16923. return null;
  16924. }
  16925. return this._gl.getShaderSource(shaders[0]);
  16926. };
  16927. /**
  16928. * Gets the source code of the fragment shader associated with a specific webGL program
  16929. * @param program defines the program to use
  16930. * @returns a string containing the source code of the fragment shader associated with the program
  16931. */
  16932. Engine.prototype.getFragmentShaderSource = function (program) {
  16933. var shaders = this._gl.getAttachedShaders(program);
  16934. if (!shaders) {
  16935. return null;
  16936. }
  16937. return this._gl.getShaderSource(shaders[1]);
  16938. };
  16939. /**
  16940. * Get the current error code of the webGL context
  16941. * @returns the error code
  16942. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16943. */
  16944. Engine.prototype.getError = function () {
  16945. return this._gl.getError();
  16946. };
  16947. // FPS
  16948. /**
  16949. * Gets the current framerate
  16950. * @returns a number representing the framerate
  16951. */
  16952. Engine.prototype.getFps = function () {
  16953. return this._fps;
  16954. };
  16955. /**
  16956. * Gets the time spent between current and previous frame
  16957. * @returns a number representing the delta time in ms
  16958. */
  16959. Engine.prototype.getDeltaTime = function () {
  16960. return this._deltaTime;
  16961. };
  16962. Engine.prototype._measureFps = function () {
  16963. this._performanceMonitor.sampleFrame();
  16964. this._fps = this._performanceMonitor.averageFPS;
  16965. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16966. };
  16967. /** @hidden */
  16968. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16969. if (faceIndex === void 0) { faceIndex = -1; }
  16970. if (level === void 0) { level = 0; }
  16971. var gl = this._gl;
  16972. if (!this._dummyFramebuffer) {
  16973. var dummy = gl.createFramebuffer();
  16974. if (!dummy) {
  16975. throw new Error("Unable to create dummy framebuffer");
  16976. }
  16977. this._dummyFramebuffer = dummy;
  16978. }
  16979. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16980. if (faceIndex > -1) {
  16981. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16982. }
  16983. else {
  16984. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16985. }
  16986. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16987. var buffer;
  16988. switch (readType) {
  16989. case gl.UNSIGNED_BYTE:
  16990. buffer = new Uint8Array(4 * width * height);
  16991. readType = gl.UNSIGNED_BYTE;
  16992. break;
  16993. default:
  16994. buffer = new Float32Array(4 * width * height);
  16995. readType = gl.FLOAT;
  16996. break;
  16997. }
  16998. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16999. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17000. return buffer;
  17001. };
  17002. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17003. if (this._webGLVersion > 1) {
  17004. return this._caps.colorBufferFloat;
  17005. }
  17006. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17007. };
  17008. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17009. if (this._webGLVersion > 1) {
  17010. return this._caps.colorBufferFloat;
  17011. }
  17012. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17013. };
  17014. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17015. Engine.prototype._canRenderToFramebuffer = function (type) {
  17016. var gl = this._gl;
  17017. //clear existing errors
  17018. while (gl.getError() !== gl.NO_ERROR) { }
  17019. var successful = true;
  17020. var texture = gl.createTexture();
  17021. gl.bindTexture(gl.TEXTURE_2D, texture);
  17022. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17023. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17024. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17025. var fb = gl.createFramebuffer();
  17026. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17028. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17029. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17030. successful = successful && (gl.getError() === gl.NO_ERROR);
  17031. //try render by clearing frame buffer's color buffer
  17032. if (successful) {
  17033. gl.clear(gl.COLOR_BUFFER_BIT);
  17034. successful = successful && (gl.getError() === gl.NO_ERROR);
  17035. }
  17036. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17037. if (successful) {
  17038. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17039. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17040. var readFormat = gl.RGBA;
  17041. var readType = gl.UNSIGNED_BYTE;
  17042. var buffer = new Uint8Array(4);
  17043. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17044. successful = successful && (gl.getError() === gl.NO_ERROR);
  17045. }
  17046. //clean up
  17047. gl.deleteTexture(texture);
  17048. gl.deleteFramebuffer(fb);
  17049. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17050. //clear accumulated errors
  17051. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17052. return successful;
  17053. };
  17054. /** @hidden */
  17055. Engine.prototype._getWebGLTextureType = function (type) {
  17056. if (type === Engine.TEXTURETYPE_FLOAT) {
  17057. return this._gl.FLOAT;
  17058. }
  17059. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17060. // Add Half Float Constant.
  17061. return this._gl.HALF_FLOAT_OES;
  17062. }
  17063. return this._gl.UNSIGNED_BYTE;
  17064. };
  17065. ;
  17066. Engine.prototype._getInternalFormat = function (format) {
  17067. var internalFormat = this._gl.RGBA;
  17068. switch (format) {
  17069. case Engine.TEXTUREFORMAT_ALPHA:
  17070. internalFormat = this._gl.ALPHA;
  17071. break;
  17072. case Engine.TEXTUREFORMAT_LUMINANCE:
  17073. internalFormat = this._gl.LUMINANCE;
  17074. break;
  17075. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17076. internalFormat = this._gl.LUMINANCE_ALPHA;
  17077. break;
  17078. case Engine.TEXTUREFORMAT_RGB:
  17079. internalFormat = this._gl.RGB;
  17080. break;
  17081. case Engine.TEXTUREFORMAT_RGBA:
  17082. internalFormat = this._gl.RGBA;
  17083. break;
  17084. case Engine.TEXTUREFORMAT_R:
  17085. internalFormat = this._gl.RED;
  17086. break;
  17087. case Engine.TEXTUREFORMAT_RG:
  17088. internalFormat = this._gl.RG;
  17089. break;
  17090. }
  17091. return internalFormat;
  17092. };
  17093. /** @hidden */
  17094. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17095. if (this._webGLVersion === 1) {
  17096. if (format !== undefined) {
  17097. switch (format) {
  17098. case Engine.TEXTUREFORMAT_LUMINANCE:
  17099. return this._gl.LUMINANCE;
  17100. case Engine.TEXTUREFORMAT_ALPHA:
  17101. return this._gl.ALPHA;
  17102. }
  17103. }
  17104. return this._gl.RGBA;
  17105. }
  17106. if (type === Engine.TEXTURETYPE_FLOAT) {
  17107. if (format !== undefined) {
  17108. switch (format) {
  17109. case Engine.TEXTUREFORMAT_R:
  17110. return this._gl.R32F;
  17111. case Engine.TEXTUREFORMAT_RG:
  17112. return this._gl.RG32F;
  17113. case Engine.TEXTUREFORMAT_RGB:
  17114. return this._gl.RGB32F;
  17115. }
  17116. }
  17117. return this._gl.RGBA32F;
  17118. }
  17119. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17120. if (format) {
  17121. switch (format) {
  17122. case Engine.TEXTUREFORMAT_R:
  17123. return this._gl.R16F;
  17124. case Engine.TEXTUREFORMAT_RG:
  17125. return this._gl.RG16F;
  17126. case Engine.TEXTUREFORMAT_RGB:
  17127. return this._gl.RGB16F;
  17128. }
  17129. }
  17130. return this._gl.RGBA16F;
  17131. }
  17132. if (format !== undefined) {
  17133. switch (format) {
  17134. case Engine.TEXTUREFORMAT_LUMINANCE:
  17135. return this._gl.LUMINANCE;
  17136. case Engine.TEXTUREFORMAT_RGB:
  17137. return this._gl.RGB;
  17138. case Engine.TEXTUREFORMAT_R:
  17139. return this._gl.R8;
  17140. case Engine.TEXTUREFORMAT_RG:
  17141. return this._gl.RG8;
  17142. case Engine.TEXTUREFORMAT_ALPHA:
  17143. return this._gl.ALPHA;
  17144. }
  17145. }
  17146. return this._gl.RGBA;
  17147. };
  17148. ;
  17149. /** @hidden */
  17150. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17151. if (type === Engine.TEXTURETYPE_FLOAT) {
  17152. return this._gl.RGBA32F;
  17153. }
  17154. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17155. return this._gl.RGBA16F;
  17156. }
  17157. return this._gl.RGBA8;
  17158. };
  17159. ;
  17160. /**
  17161. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17162. * @return the new query
  17163. */
  17164. Engine.prototype.createQuery = function () {
  17165. return this._gl.createQuery();
  17166. };
  17167. /**
  17168. * Delete and release a webGL query
  17169. * @param query defines the query to delete
  17170. * @return the current engine
  17171. */
  17172. Engine.prototype.deleteQuery = function (query) {
  17173. this._gl.deleteQuery(query);
  17174. return this;
  17175. };
  17176. /**
  17177. * Check if a given query has resolved and got its value
  17178. * @param query defines the query to check
  17179. * @returns true if the query got its value
  17180. */
  17181. Engine.prototype.isQueryResultAvailable = function (query) {
  17182. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17183. };
  17184. /**
  17185. * Gets the value of a given query
  17186. * @param query defines the query to check
  17187. * @returns the value of the query
  17188. */
  17189. Engine.prototype.getQueryResult = function (query) {
  17190. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17191. };
  17192. /**
  17193. * Initiates an occlusion query
  17194. * @param algorithmType defines the algorithm to use
  17195. * @param query defines the query to use
  17196. * @returns the current engine
  17197. * @see http://doc.babylonjs.com/features/occlusionquery
  17198. */
  17199. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17200. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17201. this._gl.beginQuery(glAlgorithm, query);
  17202. return this;
  17203. };
  17204. /**
  17205. * Ends an occlusion query
  17206. * @see http://doc.babylonjs.com/features/occlusionquery
  17207. * @param algorithmType defines the algorithm to use
  17208. * @returns the current engine
  17209. */
  17210. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17211. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17212. this._gl.endQuery(glAlgorithm);
  17213. return this;
  17214. };
  17215. /* Time queries */
  17216. Engine.prototype._createTimeQuery = function () {
  17217. var timerQuery = this._caps.timerQuery;
  17218. if (timerQuery.createQueryEXT) {
  17219. return timerQuery.createQueryEXT();
  17220. }
  17221. return this.createQuery();
  17222. };
  17223. Engine.prototype._deleteTimeQuery = function (query) {
  17224. var timerQuery = this._caps.timerQuery;
  17225. if (timerQuery.deleteQueryEXT) {
  17226. timerQuery.deleteQueryEXT(query);
  17227. return;
  17228. }
  17229. this.deleteQuery(query);
  17230. };
  17231. Engine.prototype._getTimeQueryResult = function (query) {
  17232. var timerQuery = this._caps.timerQuery;
  17233. if (timerQuery.getQueryObjectEXT) {
  17234. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17235. }
  17236. return this.getQueryResult(query);
  17237. };
  17238. Engine.prototype._getTimeQueryAvailability = function (query) {
  17239. var timerQuery = this._caps.timerQuery;
  17240. if (timerQuery.getQueryObjectEXT) {
  17241. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17242. }
  17243. return this.isQueryResultAvailable(query);
  17244. };
  17245. /**
  17246. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17247. * Please note that only one query can be issued at a time
  17248. * @returns a time token used to track the time span
  17249. */
  17250. Engine.prototype.startTimeQuery = function () {
  17251. var timerQuery = this._caps.timerQuery;
  17252. if (!timerQuery) {
  17253. return null;
  17254. }
  17255. var token = new BABYLON._TimeToken();
  17256. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17257. if (this._caps.canUseTimestampForTimerQuery) {
  17258. token._startTimeQuery = this._createTimeQuery();
  17259. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17260. }
  17261. else {
  17262. if (this._currentNonTimestampToken) {
  17263. return this._currentNonTimestampToken;
  17264. }
  17265. token._timeElapsedQuery = this._createTimeQuery();
  17266. if (timerQuery.beginQueryEXT) {
  17267. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17268. }
  17269. else {
  17270. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17271. }
  17272. this._currentNonTimestampToken = token;
  17273. }
  17274. return token;
  17275. };
  17276. /**
  17277. * Ends a time query
  17278. * @param token defines the token used to measure the time span
  17279. * @returns the time spent (in ns)
  17280. */
  17281. Engine.prototype.endTimeQuery = function (token) {
  17282. var timerQuery = this._caps.timerQuery;
  17283. if (!timerQuery || !token) {
  17284. return -1;
  17285. }
  17286. if (this._caps.canUseTimestampForTimerQuery) {
  17287. if (!token._startTimeQuery) {
  17288. return -1;
  17289. }
  17290. if (!token._endTimeQuery) {
  17291. token._endTimeQuery = this._createTimeQuery();
  17292. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17293. }
  17294. }
  17295. else if (!token._timeElapsedQueryEnded) {
  17296. if (!token._timeElapsedQuery) {
  17297. return -1;
  17298. }
  17299. if (timerQuery.endQueryEXT) {
  17300. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17301. }
  17302. else {
  17303. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17304. }
  17305. token._timeElapsedQueryEnded = true;
  17306. }
  17307. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17308. var available = false;
  17309. if (token._endTimeQuery) {
  17310. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17311. }
  17312. else if (token._timeElapsedQuery) {
  17313. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17314. }
  17315. if (available && !disjoint) {
  17316. var result = 0;
  17317. if (this._caps.canUseTimestampForTimerQuery) {
  17318. if (!token._startTimeQuery || !token._endTimeQuery) {
  17319. return -1;
  17320. }
  17321. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17322. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17323. result = timeEnd - timeStart;
  17324. this._deleteTimeQuery(token._startTimeQuery);
  17325. this._deleteTimeQuery(token._endTimeQuery);
  17326. token._startTimeQuery = null;
  17327. token._endTimeQuery = null;
  17328. }
  17329. else {
  17330. if (!token._timeElapsedQuery) {
  17331. return -1;
  17332. }
  17333. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17334. this._deleteTimeQuery(token._timeElapsedQuery);
  17335. token._timeElapsedQuery = null;
  17336. token._timeElapsedQueryEnded = false;
  17337. this._currentNonTimestampToken = null;
  17338. }
  17339. return result;
  17340. }
  17341. return -1;
  17342. };
  17343. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17344. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17345. };
  17346. // Transform feedback
  17347. /**
  17348. * Creates a webGL transform feedback object
  17349. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17350. * @returns the webGL transform feedback object
  17351. */
  17352. Engine.prototype.createTransformFeedback = function () {
  17353. return this._gl.createTransformFeedback();
  17354. };
  17355. /**
  17356. * Delete a webGL transform feedback object
  17357. * @param value defines the webGL transform feedback object to delete
  17358. */
  17359. Engine.prototype.deleteTransformFeedback = function (value) {
  17360. this._gl.deleteTransformFeedback(value);
  17361. };
  17362. /**
  17363. * Bind a webGL transform feedback object to the webgl context
  17364. * @param value defines the webGL transform feedback object to bind
  17365. */
  17366. Engine.prototype.bindTransformFeedback = function (value) {
  17367. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17368. };
  17369. /**
  17370. * Begins a transform feedback operation
  17371. * @param usePoints defines if points or triangles must be used
  17372. */
  17373. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17374. if (usePoints === void 0) { usePoints = true; }
  17375. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17376. };
  17377. /**
  17378. * Ends a transform feedback operation
  17379. */
  17380. Engine.prototype.endTransformFeedback = function () {
  17381. this._gl.endTransformFeedback();
  17382. };
  17383. /**
  17384. * Specify the varyings to use with transform feedback
  17385. * @param program defines the associated webGL program
  17386. * @param value defines the list of strings representing the varying names
  17387. */
  17388. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17389. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17390. };
  17391. /**
  17392. * Bind a webGL buffer for a transform feedback operation
  17393. * @param value defines the webGL buffer to bind
  17394. */
  17395. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17396. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17397. };
  17398. /** @hidden */
  17399. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17400. var _this = this;
  17401. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17402. this._activeRequests.push(request);
  17403. request.onCompleteObservable.add(function (request) {
  17404. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17405. });
  17406. return request;
  17407. };
  17408. /** @hidden */
  17409. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17410. var _this = this;
  17411. return new Promise(function (resolve, reject) {
  17412. _this._loadFile(url, function (data) {
  17413. resolve(data);
  17414. }, undefined, database, useArrayBuffer, function (request, exception) {
  17415. reject(exception);
  17416. });
  17417. });
  17418. };
  17419. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17420. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17421. var onload = function (data) {
  17422. loadedFiles[index] = data;
  17423. loadedFiles._internalCount++;
  17424. if (loadedFiles._internalCount === 6) {
  17425. onfinish(loadedFiles);
  17426. }
  17427. };
  17428. var onerror = function (request, exception) {
  17429. if (onErrorCallBack && request) {
  17430. onErrorCallBack(request.status + " " + request.statusText, exception);
  17431. }
  17432. };
  17433. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17434. };
  17435. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17436. if (onError === void 0) { onError = null; }
  17437. var loadedFiles = [];
  17438. loadedFiles._internalCount = 0;
  17439. for (var index = 0; index < 6; index++) {
  17440. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17441. }
  17442. };
  17443. // Statics
  17444. /**
  17445. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17446. * @returns true if the engine can be created
  17447. * @ignorenaming
  17448. */
  17449. Engine.isSupported = function () {
  17450. try {
  17451. var tempcanvas = document.createElement("canvas");
  17452. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17453. return gl != null && !!window.WebGLRenderingContext;
  17454. }
  17455. catch (e) {
  17456. return false;
  17457. }
  17458. };
  17459. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17460. Engine.ExceptionList = [
  17461. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17462. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17463. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17464. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17465. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17466. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17467. ];
  17468. /** Gets the list of created engines */
  17469. Engine.Instances = new Array();
  17470. // Const statics
  17471. Engine._ALPHA_DISABLE = 0;
  17472. Engine._ALPHA_ADD = 1;
  17473. Engine._ALPHA_COMBINE = 2;
  17474. Engine._ALPHA_SUBTRACT = 3;
  17475. Engine._ALPHA_MULTIPLY = 4;
  17476. Engine._ALPHA_MAXIMIZED = 5;
  17477. Engine._ALPHA_ONEONE = 6;
  17478. Engine._ALPHA_PREMULTIPLIED = 7;
  17479. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17480. Engine._ALPHA_INTERPOLATE = 9;
  17481. Engine._ALPHA_SCREENMODE = 10;
  17482. Engine._DELAYLOADSTATE_NONE = 0;
  17483. Engine._DELAYLOADSTATE_LOADED = 1;
  17484. Engine._DELAYLOADSTATE_LOADING = 2;
  17485. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17486. Engine._TEXTUREFORMAT_ALPHA = 0;
  17487. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17488. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17489. Engine._TEXTUREFORMAT_RGB = 4;
  17490. Engine._TEXTUREFORMAT_RGBA = 5;
  17491. Engine._TEXTUREFORMAT_R = 6;
  17492. Engine._TEXTUREFORMAT_RG = 7;
  17493. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17494. Engine._TEXTURETYPE_FLOAT = 1;
  17495. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17496. // Depht or Stencil test Constants.
  17497. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17498. 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.
  17499. 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.
  17500. 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.
  17501. 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.
  17502. 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.
  17503. 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.
  17504. 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.
  17505. // Stencil Actions Constants.
  17506. Engine._KEEP = 0x1E00;
  17507. Engine._REPLACE = 0x1E01;
  17508. Engine._INCR = 0x1E02;
  17509. Engine._DECR = 0x1E03;
  17510. Engine._INVERT = 0x150A;
  17511. Engine._INCR_WRAP = 0x8507;
  17512. Engine._DECR_WRAP = 0x8508;
  17513. // Texture rescaling mode
  17514. Engine._SCALEMODE_FLOOR = 1;
  17515. Engine._SCALEMODE_NEAREST = 2;
  17516. Engine._SCALEMODE_CEILING = 3;
  17517. // Updatable statics so stick with vars here
  17518. /**
  17519. * Gets or sets the epsilon value used by collision engine
  17520. */
  17521. Engine.CollisionsEpsilon = 0.001;
  17522. /**
  17523. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17524. */
  17525. Engine.CodeRepository = "src/";
  17526. /**
  17527. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17528. */
  17529. Engine.ShadersRepository = "src/Shaders/";
  17530. return Engine;
  17531. }());
  17532. BABYLON.Engine = Engine;
  17533. })(BABYLON || (BABYLON = {}));
  17534. //# sourceMappingURL=babylon.engine.js.map
  17535. var BABYLON;
  17536. (function (BABYLON) {
  17537. /**
  17538. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17539. */
  17540. var Node = /** @class */ (function () {
  17541. /**
  17542. * Creates a new Node
  17543. * @param {string} name - the name and id to be given to this node
  17544. * @param {BABYLON.Scene} the scene this node will be added to
  17545. */
  17546. function Node(name, scene) {
  17547. if (scene === void 0) { scene = null; }
  17548. /**
  17549. * Gets or sets a string used to store user defined state for the node
  17550. */
  17551. this.state = "";
  17552. /**
  17553. * Gets or sets an object used to store user defined information for the node
  17554. */
  17555. this.metadata = null;
  17556. /**
  17557. * Gets or sets a boolean used to define if the node must be serialized
  17558. */
  17559. this.doNotSerialize = false;
  17560. /** @hidden */
  17561. this._isDisposed = false;
  17562. /**
  17563. * Gets a list of Animations associated with the node
  17564. */
  17565. this.animations = new Array();
  17566. this._ranges = {};
  17567. this._isEnabled = true;
  17568. this._isReady = true;
  17569. /** @hidden */
  17570. this._currentRenderId = -1;
  17571. this._parentRenderId = -1;
  17572. this._childRenderId = -1;
  17573. this._animationPropertiesOverride = null;
  17574. /**
  17575. * An event triggered when the mesh is disposed
  17576. */
  17577. this.onDisposeObservable = new BABYLON.Observable();
  17578. // Behaviors
  17579. this._behaviors = new Array();
  17580. this.name = name;
  17581. this.id = name;
  17582. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17583. this.uniqueId = this._scene.getUniqueId();
  17584. this._initCache();
  17585. }
  17586. /**
  17587. * Gets a boolean indicating if the node has been disposed
  17588. * @returns true if the node was disposed
  17589. */
  17590. Node.prototype.isDisposed = function () {
  17591. return this._isDisposed;
  17592. };
  17593. Object.defineProperty(Node.prototype, "parent", {
  17594. get: function () {
  17595. return this._parentNode;
  17596. },
  17597. /**
  17598. * Gets or sets the parent of the node
  17599. */
  17600. set: function (parent) {
  17601. if (this._parentNode === parent) {
  17602. return;
  17603. }
  17604. // Remove self from list of children of parent
  17605. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17606. var index = this._parentNode._children.indexOf(this);
  17607. if (index !== -1) {
  17608. this._parentNode._children.splice(index, 1);
  17609. }
  17610. }
  17611. // Store new parent
  17612. this._parentNode = parent;
  17613. // Add as child to new parent
  17614. if (this._parentNode) {
  17615. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17616. this._parentNode._children = new Array();
  17617. }
  17618. this._parentNode._children.push(this);
  17619. }
  17620. },
  17621. enumerable: true,
  17622. configurable: true
  17623. });
  17624. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17625. /**
  17626. * Gets or sets the animation properties override
  17627. */
  17628. get: function () {
  17629. if (!this._animationPropertiesOverride) {
  17630. return this._scene.animationPropertiesOverride;
  17631. }
  17632. return this._animationPropertiesOverride;
  17633. },
  17634. set: function (value) {
  17635. this._animationPropertiesOverride = value;
  17636. },
  17637. enumerable: true,
  17638. configurable: true
  17639. });
  17640. /**
  17641. * Gets a string idenfifying the name of the class
  17642. * @returns "Node" string
  17643. */
  17644. Node.prototype.getClassName = function () {
  17645. return "Node";
  17646. };
  17647. Object.defineProperty(Node.prototype, "onDispose", {
  17648. /**
  17649. * Sets a callback that will be raised when the node will be disposed
  17650. */
  17651. set: function (callback) {
  17652. if (this._onDisposeObserver) {
  17653. this.onDisposeObservable.remove(this._onDisposeObserver);
  17654. }
  17655. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. /**
  17661. * Gets the scene of the node
  17662. * @returns a {BABYLON.Scene}
  17663. */
  17664. Node.prototype.getScene = function () {
  17665. return this._scene;
  17666. };
  17667. /**
  17668. * Gets the engine of the node
  17669. * @returns a {BABYLON.Engine}
  17670. */
  17671. Node.prototype.getEngine = function () {
  17672. return this._scene.getEngine();
  17673. };
  17674. /**
  17675. * Attach a behavior to the node
  17676. * @see http://doc.babylonjs.com/features/behaviour
  17677. * @param behavior defines the behavior to attach
  17678. * @returns the current Node
  17679. */
  17680. Node.prototype.addBehavior = function (behavior) {
  17681. var _this = this;
  17682. var index = this._behaviors.indexOf(behavior);
  17683. if (index !== -1) {
  17684. return this;
  17685. }
  17686. behavior.init();
  17687. if (this._scene.isLoading) {
  17688. // We defer the attach when the scene will be loaded
  17689. this._scene.onDataLoadedObservable.addOnce(function () {
  17690. behavior.attach(_this);
  17691. });
  17692. }
  17693. else {
  17694. behavior.attach(this);
  17695. }
  17696. this._behaviors.push(behavior);
  17697. return this;
  17698. };
  17699. /**
  17700. * Remove an attached behavior
  17701. * @see http://doc.babylonjs.com/features/behaviour
  17702. * @param behavior defines the behavior to attach
  17703. * @returns the current Node
  17704. */
  17705. Node.prototype.removeBehavior = function (behavior) {
  17706. var index = this._behaviors.indexOf(behavior);
  17707. if (index === -1) {
  17708. return this;
  17709. }
  17710. this._behaviors[index].detach();
  17711. this._behaviors.splice(index, 1);
  17712. return this;
  17713. };
  17714. Object.defineProperty(Node.prototype, "behaviors", {
  17715. /**
  17716. * Gets the list of attached behaviors
  17717. * @see http://doc.babylonjs.com/features/behaviour
  17718. */
  17719. get: function () {
  17720. return this._behaviors;
  17721. },
  17722. enumerable: true,
  17723. configurable: true
  17724. });
  17725. /**
  17726. * Gets an attached behavior by name
  17727. * @param name defines the name of the behavior to look for
  17728. * @see http://doc.babylonjs.com/features/behaviour
  17729. * @returns null if behavior was not found else the requested behavior
  17730. */
  17731. Node.prototype.getBehaviorByName = function (name) {
  17732. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17733. var behavior = _a[_i];
  17734. if (behavior.name === name) {
  17735. return behavior;
  17736. }
  17737. }
  17738. return null;
  17739. };
  17740. /**
  17741. * Returns the world matrix of the node
  17742. * @returns a matrix containing the node's world matrix
  17743. */
  17744. Node.prototype.getWorldMatrix = function () {
  17745. return BABYLON.Matrix.Identity();
  17746. };
  17747. /** @hidden */
  17748. Node.prototype._getWorldMatrixDeterminant = function () {
  17749. return 1;
  17750. };
  17751. // override it in derived class if you add new variables to the cache
  17752. // and call the parent class method
  17753. /** @hidden */
  17754. Node.prototype._initCache = function () {
  17755. this._cache = {};
  17756. this._cache.parent = undefined;
  17757. };
  17758. /** @hidden */
  17759. Node.prototype.updateCache = function (force) {
  17760. if (!force && this.isSynchronized())
  17761. return;
  17762. this._cache.parent = this.parent;
  17763. this._updateCache();
  17764. };
  17765. // override it in derived class if you add new variables to the cache
  17766. // and call the parent class method if !ignoreParentClass
  17767. /** @hidden */
  17768. Node.prototype._updateCache = function (ignoreParentClass) {
  17769. };
  17770. // override it in derived class if you add new variables to the cache
  17771. /** @hidden */
  17772. Node.prototype._isSynchronized = function () {
  17773. return true;
  17774. };
  17775. /** @hidden */
  17776. Node.prototype._markSyncedWithParent = function () {
  17777. if (this.parent) {
  17778. this._parentRenderId = this.parent._childRenderId;
  17779. }
  17780. };
  17781. /** @hidden */
  17782. Node.prototype.isSynchronizedWithParent = function () {
  17783. if (!this.parent) {
  17784. return true;
  17785. }
  17786. if (this._parentRenderId !== this.parent._childRenderId) {
  17787. return false;
  17788. }
  17789. return this.parent.isSynchronized();
  17790. };
  17791. /** @hidden */
  17792. Node.prototype.isSynchronized = function (updateCache) {
  17793. var check = this.hasNewParent();
  17794. check = check || !this.isSynchronizedWithParent();
  17795. check = check || !this._isSynchronized();
  17796. if (updateCache)
  17797. this.updateCache(true);
  17798. return !check;
  17799. };
  17800. /** @hidden */
  17801. Node.prototype.hasNewParent = function (update) {
  17802. if (this._cache.parent === this.parent)
  17803. return false;
  17804. if (update)
  17805. this._cache.parent = this.parent;
  17806. return true;
  17807. };
  17808. /**
  17809. * Is this node ready to be used/rendered
  17810. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17811. * @return true if the node is ready
  17812. */
  17813. Node.prototype.isReady = function (completeCheck) {
  17814. if (completeCheck === void 0) { completeCheck = false; }
  17815. return this._isReady;
  17816. };
  17817. /**
  17818. * Is this node enabled?
  17819. * 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
  17820. * @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
  17821. * @return whether this node (and its parent) is enabled
  17822. */
  17823. Node.prototype.isEnabled = function (checkAncestors) {
  17824. if (checkAncestors === void 0) { checkAncestors = true; }
  17825. if (checkAncestors === false) {
  17826. return this._isEnabled;
  17827. }
  17828. if (this._isEnabled === false) {
  17829. return false;
  17830. }
  17831. if (this.parent !== undefined && this.parent !== null) {
  17832. return this.parent.isEnabled(checkAncestors);
  17833. }
  17834. return true;
  17835. };
  17836. /**
  17837. * Set the enabled state of this node
  17838. * @param value defines the new enabled state
  17839. */
  17840. Node.prototype.setEnabled = function (value) {
  17841. this._isEnabled = value;
  17842. };
  17843. /**
  17844. * Is this node a descendant of the given node?
  17845. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17846. * @param ancestor defines the parent node to inspect
  17847. * @returns a boolean indicating if this node is a descendant of the given node
  17848. */
  17849. Node.prototype.isDescendantOf = function (ancestor) {
  17850. if (this.parent) {
  17851. if (this.parent === ancestor) {
  17852. return true;
  17853. }
  17854. return this.parent.isDescendantOf(ancestor);
  17855. }
  17856. return false;
  17857. };
  17858. /** @hidden */
  17859. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17860. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17861. if (!this._children) {
  17862. return;
  17863. }
  17864. for (var index = 0; index < this._children.length; index++) {
  17865. var item = this._children[index];
  17866. if (!predicate || predicate(item)) {
  17867. results.push(item);
  17868. }
  17869. if (!directDescendantsOnly) {
  17870. item._getDescendants(results, false, predicate);
  17871. }
  17872. }
  17873. };
  17874. /**
  17875. * Will return all nodes that have this node as ascendant
  17876. * @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
  17877. * @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
  17878. * @return all children nodes of all types
  17879. */
  17880. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17881. var results = new Array();
  17882. this._getDescendants(results, directDescendantsOnly, predicate);
  17883. return results;
  17884. };
  17885. /**
  17886. * Get all child-meshes of this node
  17887. * @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
  17888. * @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
  17889. * @returns an array of {BABYLON.AbstractMesh}
  17890. */
  17891. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17892. var results = [];
  17893. this._getDescendants(results, directDescendantsOnly, function (node) {
  17894. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17895. });
  17896. return results;
  17897. };
  17898. /**
  17899. * Get all child-transformNodes of this node
  17900. * @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
  17901. * @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
  17902. * @returns an array of {BABYLON.TransformNode}
  17903. */
  17904. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17905. var results = [];
  17906. this._getDescendants(results, directDescendantsOnly, function (node) {
  17907. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17908. });
  17909. return results;
  17910. };
  17911. /**
  17912. * Get all direct children of this node
  17913. * @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
  17914. * @returns an array of {BABYLON.Node}
  17915. */
  17916. Node.prototype.getChildren = function (predicate) {
  17917. return this.getDescendants(true, predicate);
  17918. };
  17919. /** @hidden */
  17920. Node.prototype._setReady = function (state) {
  17921. if (state === this._isReady) {
  17922. return;
  17923. }
  17924. if (!state) {
  17925. this._isReady = false;
  17926. return;
  17927. }
  17928. if (this.onReady) {
  17929. this.onReady(this);
  17930. }
  17931. this._isReady = true;
  17932. };
  17933. /**
  17934. * Get an animation by name
  17935. * @param name defines the name of the animation to look for
  17936. * @returns null if not found else the requested animation
  17937. */
  17938. Node.prototype.getAnimationByName = function (name) {
  17939. for (var i = 0; i < this.animations.length; i++) {
  17940. var animation = this.animations[i];
  17941. if (animation.name === name) {
  17942. return animation;
  17943. }
  17944. }
  17945. return null;
  17946. };
  17947. /**
  17948. * Creates an animation range for this node
  17949. * @param name defines the name of the range
  17950. * @param from defines the starting key
  17951. * @param to defines the end key
  17952. */
  17953. Node.prototype.createAnimationRange = function (name, from, to) {
  17954. // check name not already in use
  17955. if (!this._ranges[name]) {
  17956. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17957. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17958. if (this.animations[i]) {
  17959. this.animations[i].createRange(name, from, to);
  17960. }
  17961. }
  17962. }
  17963. };
  17964. /**
  17965. * Delete a specific animation range
  17966. * @param name defines the name of the range to delete
  17967. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17968. */
  17969. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17970. if (deleteFrames === void 0) { deleteFrames = true; }
  17971. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17972. if (this.animations[i]) {
  17973. this.animations[i].deleteRange(name, deleteFrames);
  17974. }
  17975. }
  17976. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17977. };
  17978. /**
  17979. * Get an animation range by name
  17980. * @param name defines the name of the animation range to look for
  17981. * @returns null if not found else the requested animation range
  17982. */
  17983. Node.prototype.getAnimationRange = function (name) {
  17984. return this._ranges[name];
  17985. };
  17986. /**
  17987. * Will start the animation sequence
  17988. * @param name defines the range frames for animation sequence
  17989. * @param loop defines if the animation should loop (false by default)
  17990. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17991. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17992. * @returns the object created for this animation. If range does not exist, it will return null
  17993. */
  17994. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17995. var range = this.getAnimationRange(name);
  17996. if (!range) {
  17997. return null;
  17998. }
  17999. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18000. };
  18001. /**
  18002. * Serialize animation ranges into a JSON compatible object
  18003. * @returns serialization object
  18004. */
  18005. Node.prototype.serializeAnimationRanges = function () {
  18006. var serializationRanges = [];
  18007. for (var name in this._ranges) {
  18008. var localRange = this._ranges[name];
  18009. if (!localRange) {
  18010. continue;
  18011. }
  18012. var range = {};
  18013. range.name = name;
  18014. range.from = localRange.from;
  18015. range.to = localRange.to;
  18016. serializationRanges.push(range);
  18017. }
  18018. return serializationRanges;
  18019. };
  18020. /**
  18021. * Computes the world matrix of the node
  18022. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18023. * @returns the world matrix
  18024. */
  18025. Node.prototype.computeWorldMatrix = function (force) {
  18026. return BABYLON.Matrix.Identity();
  18027. };
  18028. /**
  18029. * Releases resources associated with this node.
  18030. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18031. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18032. */
  18033. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18034. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18035. if (!doNotRecurse) {
  18036. var nodes = this.getDescendants(true);
  18037. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18038. var node = nodes_1[_i];
  18039. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18040. }
  18041. }
  18042. else {
  18043. var transformNodes = this.getChildTransformNodes(true);
  18044. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18045. var transformNode = transformNodes_1[_a];
  18046. transformNode.parent = null;
  18047. transformNode.computeWorldMatrix(true);
  18048. }
  18049. }
  18050. this.parent = null;
  18051. // Callback
  18052. this.onDisposeObservable.notifyObservers(this);
  18053. this.onDisposeObservable.clear();
  18054. // Behaviors
  18055. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18056. var behavior = _c[_b];
  18057. behavior.detach();
  18058. }
  18059. this._behaviors = [];
  18060. this._isDisposed = true;
  18061. };
  18062. /**
  18063. * Parse animation range data from a serialization object and store them into a given node
  18064. * @param node defines where to store the animation ranges
  18065. * @param parsedNode defines the serialization object to read data from
  18066. * @param scene defines the hosting scene
  18067. */
  18068. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18069. if (parsedNode.ranges) {
  18070. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18071. var data = parsedNode.ranges[index];
  18072. node.createAnimationRange(data.name, data.from, data.to);
  18073. }
  18074. }
  18075. };
  18076. __decorate([
  18077. BABYLON.serialize()
  18078. ], Node.prototype, "name", void 0);
  18079. __decorate([
  18080. BABYLON.serialize()
  18081. ], Node.prototype, "id", void 0);
  18082. __decorate([
  18083. BABYLON.serialize()
  18084. ], Node.prototype, "uniqueId", void 0);
  18085. __decorate([
  18086. BABYLON.serialize()
  18087. ], Node.prototype, "state", void 0);
  18088. __decorate([
  18089. BABYLON.serialize()
  18090. ], Node.prototype, "metadata", void 0);
  18091. return Node;
  18092. }());
  18093. BABYLON.Node = Node;
  18094. })(BABYLON || (BABYLON = {}));
  18095. //# sourceMappingURL=babylon.node.js.map
  18096. var BABYLON;
  18097. (function (BABYLON) {
  18098. var BoundingSphere = /** @class */ (function () {
  18099. /**
  18100. * Creates a new bounding sphere
  18101. * @param min defines the minimum vector (in local space)
  18102. * @param max defines the maximum vector (in local space)
  18103. */
  18104. function BoundingSphere(min, max) {
  18105. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18106. this.reConstruct(min, max);
  18107. }
  18108. /**
  18109. * Recreates the entire bounding sphere from scratch
  18110. * @param min defines the new minimum vector (in local space)
  18111. * @param max defines the new maximum vector (in local space)
  18112. */
  18113. BoundingSphere.prototype.reConstruct = function (min, max) {
  18114. this.minimum = min.clone();
  18115. this.maximum = max.clone();
  18116. var distance = BABYLON.Vector3.Distance(min, max);
  18117. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18118. this.radius = distance * 0.5;
  18119. this.centerWorld = BABYLON.Vector3.Zero();
  18120. this._update(BABYLON.Matrix.Identity());
  18121. };
  18122. // Methods
  18123. BoundingSphere.prototype._update = function (world) {
  18124. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18125. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18126. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18127. };
  18128. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18129. for (var i = 0; i < 6; i++) {
  18130. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18131. return false;
  18132. }
  18133. return true;
  18134. };
  18135. BoundingSphere.prototype.intersectsPoint = function (point) {
  18136. var x = this.centerWorld.x - point.x;
  18137. var y = this.centerWorld.y - point.y;
  18138. var z = this.centerWorld.z - point.z;
  18139. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18140. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18141. return false;
  18142. return true;
  18143. };
  18144. // Statics
  18145. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18146. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18147. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18148. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18149. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18150. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18151. return false;
  18152. return true;
  18153. };
  18154. return BoundingSphere;
  18155. }());
  18156. BABYLON.BoundingSphere = BoundingSphere;
  18157. })(BABYLON || (BABYLON = {}));
  18158. //# sourceMappingURL=babylon.boundingSphere.js.map
  18159. var BABYLON;
  18160. (function (BABYLON) {
  18161. var BoundingBox = /** @class */ (function () {
  18162. /**
  18163. * Creates a new bounding box
  18164. * @param min defines the minimum vector (in local space)
  18165. * @param max defines the maximum vector (in local space)
  18166. */
  18167. function BoundingBox(min, max) {
  18168. this.vectorsWorld = new Array();
  18169. this.reConstruct(min, max);
  18170. }
  18171. // Methods
  18172. /**
  18173. * Recreates the entire bounding box from scratch
  18174. * @param min defines the new minimum vector (in local space)
  18175. * @param max defines the new maximum vector (in local space)
  18176. */
  18177. BoundingBox.prototype.reConstruct = function (min, max) {
  18178. this.minimum = min.clone();
  18179. this.maximum = max.clone();
  18180. // Bounding vectors
  18181. this.vectors = new Array();
  18182. this.vectors.push(this.minimum.clone());
  18183. this.vectors.push(this.maximum.clone());
  18184. this.vectors.push(this.minimum.clone());
  18185. this.vectors[2].x = this.maximum.x;
  18186. this.vectors.push(this.minimum.clone());
  18187. this.vectors[3].y = this.maximum.y;
  18188. this.vectors.push(this.minimum.clone());
  18189. this.vectors[4].z = this.maximum.z;
  18190. this.vectors.push(this.maximum.clone());
  18191. this.vectors[5].z = this.minimum.z;
  18192. this.vectors.push(this.maximum.clone());
  18193. this.vectors[6].x = this.minimum.x;
  18194. this.vectors.push(this.maximum.clone());
  18195. this.vectors[7].y = this.minimum.y;
  18196. // OBB
  18197. this.center = this.maximum.add(this.minimum).scale(0.5);
  18198. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18199. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18200. // World
  18201. for (var index = 0; index < this.vectors.length; index++) {
  18202. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18203. }
  18204. this.minimumWorld = BABYLON.Vector3.Zero();
  18205. this.maximumWorld = BABYLON.Vector3.Zero();
  18206. this.centerWorld = BABYLON.Vector3.Zero();
  18207. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18208. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18209. };
  18210. BoundingBox.prototype.getWorldMatrix = function () {
  18211. return this._worldMatrix;
  18212. };
  18213. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18214. this._worldMatrix.copyFrom(matrix);
  18215. return this;
  18216. };
  18217. BoundingBox.prototype._update = function (world) {
  18218. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18219. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18220. for (var index = 0; index < this.vectors.length; index++) {
  18221. var v = this.vectorsWorld[index];
  18222. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18223. if (v.x < this.minimumWorld.x)
  18224. this.minimumWorld.x = v.x;
  18225. if (v.y < this.minimumWorld.y)
  18226. this.minimumWorld.y = v.y;
  18227. if (v.z < this.minimumWorld.z)
  18228. this.minimumWorld.z = v.z;
  18229. if (v.x > this.maximumWorld.x)
  18230. this.maximumWorld.x = v.x;
  18231. if (v.y > this.maximumWorld.y)
  18232. this.maximumWorld.y = v.y;
  18233. if (v.z > this.maximumWorld.z)
  18234. this.maximumWorld.z = v.z;
  18235. }
  18236. // Extend
  18237. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18238. this.extendSizeWorld.scaleInPlace(0.5);
  18239. // OBB
  18240. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18241. this.centerWorld.scaleInPlace(0.5);
  18242. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18243. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18244. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18245. this._worldMatrix = world;
  18246. };
  18247. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18248. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18249. };
  18250. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18251. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18252. };
  18253. BoundingBox.prototype.intersectsPoint = function (point) {
  18254. var delta = -BABYLON.Epsilon;
  18255. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18256. return false;
  18257. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18258. return false;
  18259. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18260. return false;
  18261. return true;
  18262. };
  18263. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18264. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18265. };
  18266. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18267. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18268. return false;
  18269. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18270. return false;
  18271. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18272. return false;
  18273. return true;
  18274. };
  18275. // Statics
  18276. BoundingBox.Intersects = function (box0, box1) {
  18277. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18278. return false;
  18279. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18280. return false;
  18281. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18282. return false;
  18283. return true;
  18284. };
  18285. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18286. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18287. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18288. return (num <= (sphereRadius * sphereRadius));
  18289. };
  18290. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18291. for (var p = 0; p < 6; p++) {
  18292. for (var i = 0; i < 8; i++) {
  18293. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18294. return false;
  18295. }
  18296. }
  18297. }
  18298. return true;
  18299. };
  18300. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18301. for (var p = 0; p < 6; p++) {
  18302. var inCount = 8;
  18303. for (var i = 0; i < 8; i++) {
  18304. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18305. --inCount;
  18306. }
  18307. else {
  18308. break;
  18309. }
  18310. }
  18311. if (inCount === 0)
  18312. return false;
  18313. }
  18314. return true;
  18315. };
  18316. return BoundingBox;
  18317. }());
  18318. BABYLON.BoundingBox = BoundingBox;
  18319. })(BABYLON || (BABYLON = {}));
  18320. //# sourceMappingURL=babylon.boundingBox.js.map
  18321. var BABYLON;
  18322. (function (BABYLON) {
  18323. var computeBoxExtents = function (axis, box) {
  18324. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18325. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18326. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18327. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18328. var r = r0 + r1 + r2;
  18329. return {
  18330. min: p - r,
  18331. max: p + r
  18332. };
  18333. };
  18334. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18335. var axisOverlap = function (axis, box0, box1) {
  18336. var result0 = computeBoxExtents(axis, box0);
  18337. var result1 = computeBoxExtents(axis, box1);
  18338. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18339. };
  18340. var BoundingInfo = /** @class */ (function () {
  18341. function BoundingInfo(minimum, maximum) {
  18342. this.minimum = minimum;
  18343. this.maximum = maximum;
  18344. this._isLocked = false;
  18345. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18346. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18347. }
  18348. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18349. get: function () {
  18350. return this._isLocked;
  18351. },
  18352. set: function (value) {
  18353. this._isLocked = value;
  18354. },
  18355. enumerable: true,
  18356. configurable: true
  18357. });
  18358. // Methods
  18359. BoundingInfo.prototype.update = function (world) {
  18360. if (this._isLocked) {
  18361. return;
  18362. }
  18363. this.boundingBox._update(world);
  18364. this.boundingSphere._update(world);
  18365. };
  18366. /**
  18367. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18368. * @param center New center of the bounding info
  18369. * @param extend New extend of the bounding info
  18370. */
  18371. BoundingInfo.prototype.centerOn = function (center, extend) {
  18372. this.minimum = center.subtract(extend);
  18373. this.maximum = center.add(extend);
  18374. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18375. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18376. return this;
  18377. };
  18378. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18379. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18380. return false;
  18381. return this.boundingBox.isInFrustum(frustumPlanes);
  18382. };
  18383. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18384. /**
  18385. * Gets the world distance between the min and max points of the bounding box
  18386. */
  18387. get: function () {
  18388. var boundingBox = this.boundingBox;
  18389. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18390. return size.length();
  18391. },
  18392. enumerable: true,
  18393. configurable: true
  18394. });
  18395. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18396. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18397. };
  18398. BoundingInfo.prototype._checkCollision = function (collider) {
  18399. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18400. };
  18401. BoundingInfo.prototype.intersectsPoint = function (point) {
  18402. if (!this.boundingSphere.centerWorld) {
  18403. return false;
  18404. }
  18405. if (!this.boundingSphere.intersectsPoint(point)) {
  18406. return false;
  18407. }
  18408. if (!this.boundingBox.intersectsPoint(point)) {
  18409. return false;
  18410. }
  18411. return true;
  18412. };
  18413. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18414. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18415. return false;
  18416. }
  18417. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18418. return false;
  18419. }
  18420. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18421. return false;
  18422. }
  18423. if (!precise) {
  18424. return true;
  18425. }
  18426. var box0 = this.boundingBox;
  18427. var box1 = boundingInfo.boundingBox;
  18428. if (!axisOverlap(box0.directions[0], box0, box1))
  18429. return false;
  18430. if (!axisOverlap(box0.directions[1], box0, box1))
  18431. return false;
  18432. if (!axisOverlap(box0.directions[2], box0, box1))
  18433. return false;
  18434. if (!axisOverlap(box1.directions[0], box0, box1))
  18435. return false;
  18436. if (!axisOverlap(box1.directions[1], box0, box1))
  18437. return false;
  18438. if (!axisOverlap(box1.directions[2], box0, box1))
  18439. return false;
  18440. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18441. return false;
  18442. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18443. return false;
  18444. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18445. return false;
  18446. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18447. return false;
  18448. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18449. return false;
  18450. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18451. return false;
  18452. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18453. return false;
  18454. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18455. return false;
  18456. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18457. return false;
  18458. return true;
  18459. };
  18460. return BoundingInfo;
  18461. }());
  18462. BABYLON.BoundingInfo = BoundingInfo;
  18463. })(BABYLON || (BABYLON = {}));
  18464. //# sourceMappingURL=babylon.boundingInfo.js.map
  18465. var BABYLON;
  18466. (function (BABYLON) {
  18467. var TransformNode = /** @class */ (function (_super) {
  18468. __extends(TransformNode, _super);
  18469. function TransformNode(name, scene, isPure) {
  18470. if (scene === void 0) { scene = null; }
  18471. if (isPure === void 0) { isPure = true; }
  18472. var _this = _super.call(this, name, scene) || this;
  18473. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18474. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18475. _this._up = new BABYLON.Vector3(0, 1, 0);
  18476. _this._right = new BABYLON.Vector3(1, 0, 0);
  18477. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18478. // Properties
  18479. _this._rotation = BABYLON.Vector3.Zero();
  18480. _this._scaling = BABYLON.Vector3.One();
  18481. _this._isDirty = false;
  18482. /**
  18483. * Set the billboard mode. Default is 0.
  18484. *
  18485. * | Value | Type | Description |
  18486. * | --- | --- | --- |
  18487. * | 0 | BILLBOARDMODE_NONE | |
  18488. * | 1 | BILLBOARDMODE_X | |
  18489. * | 2 | BILLBOARDMODE_Y | |
  18490. * | 4 | BILLBOARDMODE_Z | |
  18491. * | 7 | BILLBOARDMODE_ALL | |
  18492. *
  18493. */
  18494. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18495. _this.scalingDeterminant = 1;
  18496. _this.infiniteDistance = false;
  18497. /**
  18498. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18499. * By default the system will update normals to compensate
  18500. */
  18501. _this.ignoreNonUniformScaling = false;
  18502. _this.position = BABYLON.Vector3.Zero();
  18503. _this._localWorld = BABYLON.Matrix.Zero();
  18504. _this._worldMatrix = BABYLON.Matrix.Zero();
  18505. _this._worldMatrixDeterminant = 0;
  18506. _this._absolutePosition = BABYLON.Vector3.Zero();
  18507. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18508. _this._postMultiplyPivotMatrix = false;
  18509. _this._isWorldMatrixFrozen = false;
  18510. /**
  18511. * An event triggered after the world matrix is updated
  18512. */
  18513. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18514. _this._nonUniformScaling = false;
  18515. if (isPure) {
  18516. _this.getScene().addTransformNode(_this);
  18517. }
  18518. return _this;
  18519. }
  18520. /**
  18521. * Gets a string idenfifying the name of the class
  18522. * @returns "TransformNode" string
  18523. */
  18524. TransformNode.prototype.getClassName = function () {
  18525. return "TransformNode";
  18526. };
  18527. Object.defineProperty(TransformNode.prototype, "rotation", {
  18528. /**
  18529. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18530. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18531. * Default : (0.0, 0.0, 0.0)
  18532. */
  18533. get: function () {
  18534. return this._rotation;
  18535. },
  18536. set: function (newRotation) {
  18537. this._rotation = newRotation;
  18538. },
  18539. enumerable: true,
  18540. configurable: true
  18541. });
  18542. Object.defineProperty(TransformNode.prototype, "scaling", {
  18543. /**
  18544. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18545. * Default : (1.0, 1.0, 1.0)
  18546. */
  18547. get: function () {
  18548. return this._scaling;
  18549. },
  18550. /**
  18551. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18552. * Default : (1.0, 1.0, 1.0)
  18553. */
  18554. set: function (newScaling) {
  18555. this._scaling = newScaling;
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18561. /**
  18562. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18563. * It's null by default.
  18564. * 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)
  18565. */
  18566. get: function () {
  18567. return this._rotationQuaternion;
  18568. },
  18569. set: function (quaternion) {
  18570. this._rotationQuaternion = quaternion;
  18571. //reset the rotation vector.
  18572. if (quaternion && this.rotation.length()) {
  18573. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18574. }
  18575. },
  18576. enumerable: true,
  18577. configurable: true
  18578. });
  18579. Object.defineProperty(TransformNode.prototype, "forward", {
  18580. /**
  18581. * The forward direction of that transform in world space.
  18582. */
  18583. get: function () {
  18584. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18585. },
  18586. enumerable: true,
  18587. configurable: true
  18588. });
  18589. Object.defineProperty(TransformNode.prototype, "up", {
  18590. /**
  18591. * The up direction of that transform in world space.
  18592. */
  18593. get: function () {
  18594. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18595. },
  18596. enumerable: true,
  18597. configurable: true
  18598. });
  18599. Object.defineProperty(TransformNode.prototype, "right", {
  18600. /**
  18601. * The right direction of that transform in world space.
  18602. */
  18603. get: function () {
  18604. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18605. },
  18606. enumerable: true,
  18607. configurable: true
  18608. });
  18609. /**
  18610. * Returns the latest update of the World matrix
  18611. * Returns a Matrix.
  18612. */
  18613. TransformNode.prototype.getWorldMatrix = function () {
  18614. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18615. this.computeWorldMatrix();
  18616. }
  18617. return this._worldMatrix;
  18618. };
  18619. /** @hidden */
  18620. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18621. return this._worldMatrixDeterminant;
  18622. };
  18623. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18624. /**
  18625. * Returns directly the latest state of the mesh World matrix.
  18626. * A Matrix is returned.
  18627. */
  18628. get: function () {
  18629. return this._worldMatrix;
  18630. },
  18631. enumerable: true,
  18632. configurable: true
  18633. });
  18634. /**
  18635. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18636. * Returns the TransformNode.
  18637. */
  18638. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18639. this._poseMatrix.copyFrom(matrix);
  18640. return this;
  18641. };
  18642. /**
  18643. * Returns the mesh Pose matrix.
  18644. * Returned object : Matrix
  18645. */
  18646. TransformNode.prototype.getPoseMatrix = function () {
  18647. return this._poseMatrix;
  18648. };
  18649. TransformNode.prototype._isSynchronized = function () {
  18650. if (this._isDirty) {
  18651. return false;
  18652. }
  18653. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18654. return false;
  18655. if (this._cache.pivotMatrixUpdated) {
  18656. return false;
  18657. }
  18658. if (this.infiniteDistance) {
  18659. return false;
  18660. }
  18661. if (!this._cache.position.equals(this.position))
  18662. return false;
  18663. if (this.rotationQuaternion) {
  18664. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18665. return false;
  18666. }
  18667. if (!this._cache.rotation.equals(this.rotation))
  18668. return false;
  18669. if (!this._cache.scaling.equals(this.scaling))
  18670. return false;
  18671. return true;
  18672. };
  18673. TransformNode.prototype._initCache = function () {
  18674. _super.prototype._initCache.call(this);
  18675. this._cache.localMatrixUpdated = false;
  18676. this._cache.position = BABYLON.Vector3.Zero();
  18677. this._cache.scaling = BABYLON.Vector3.Zero();
  18678. this._cache.rotation = BABYLON.Vector3.Zero();
  18679. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18680. this._cache.billboardMode = -1;
  18681. };
  18682. TransformNode.prototype.markAsDirty = function (property) {
  18683. if (property === "rotation") {
  18684. this.rotationQuaternion = null;
  18685. }
  18686. this._currentRenderId = Number.MAX_VALUE;
  18687. this._isDirty = true;
  18688. return this;
  18689. };
  18690. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18691. /**
  18692. * Returns the current mesh absolute position.
  18693. * Retuns a Vector3.
  18694. */
  18695. get: function () {
  18696. return this._absolutePosition;
  18697. },
  18698. enumerable: true,
  18699. configurable: true
  18700. });
  18701. /**
  18702. * Sets a new matrix to apply before all other transformation
  18703. * @param matrix defines the transform matrix
  18704. * @returns the current TransformNode
  18705. */
  18706. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18707. return this.setPivotMatrix(matrix, false);
  18708. };
  18709. /**
  18710. * Sets a new pivot matrix to the current node
  18711. * @param matrix defines the new pivot matrix to use
  18712. * @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
  18713. * @returns the current TransformNode
  18714. */
  18715. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18716. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18717. this._pivotMatrix = matrix.clone();
  18718. this._cache.pivotMatrixUpdated = true;
  18719. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18720. if (this._postMultiplyPivotMatrix) {
  18721. if (!this._pivotMatrixInverse) {
  18722. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18723. }
  18724. else {
  18725. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18726. }
  18727. }
  18728. return this;
  18729. };
  18730. /**
  18731. * Returns the mesh pivot matrix.
  18732. * Default : Identity.
  18733. * A Matrix is returned.
  18734. */
  18735. TransformNode.prototype.getPivotMatrix = function () {
  18736. return this._pivotMatrix;
  18737. };
  18738. /**
  18739. * Prevents the World matrix to be computed any longer.
  18740. * Returns the TransformNode.
  18741. */
  18742. TransformNode.prototype.freezeWorldMatrix = function () {
  18743. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18744. this.computeWorldMatrix(true);
  18745. this._isWorldMatrixFrozen = true;
  18746. return this;
  18747. };
  18748. /**
  18749. * Allows back the World matrix computation.
  18750. * Returns the TransformNode.
  18751. */
  18752. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18753. this._isWorldMatrixFrozen = false;
  18754. this.computeWorldMatrix(true);
  18755. return this;
  18756. };
  18757. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18758. /**
  18759. * True if the World matrix has been frozen.
  18760. * Returns a boolean.
  18761. */
  18762. get: function () {
  18763. return this._isWorldMatrixFrozen;
  18764. },
  18765. enumerable: true,
  18766. configurable: true
  18767. });
  18768. /**
  18769. * Retuns the mesh absolute position in the World.
  18770. * Returns a Vector3.
  18771. */
  18772. TransformNode.prototype.getAbsolutePosition = function () {
  18773. this.computeWorldMatrix();
  18774. return this._absolutePosition;
  18775. };
  18776. /**
  18777. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18778. * Returns the TransformNode.
  18779. */
  18780. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18781. if (!absolutePosition) {
  18782. return this;
  18783. }
  18784. var absolutePositionX;
  18785. var absolutePositionY;
  18786. var absolutePositionZ;
  18787. if (absolutePosition.x === undefined) {
  18788. if (arguments.length < 3) {
  18789. return this;
  18790. }
  18791. absolutePositionX = arguments[0];
  18792. absolutePositionY = arguments[1];
  18793. absolutePositionZ = arguments[2];
  18794. }
  18795. else {
  18796. absolutePositionX = absolutePosition.x;
  18797. absolutePositionY = absolutePosition.y;
  18798. absolutePositionZ = absolutePosition.z;
  18799. }
  18800. if (this.parent) {
  18801. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18802. invertParentWorldMatrix.invert();
  18803. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18804. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18805. }
  18806. else {
  18807. this.position.x = absolutePositionX;
  18808. this.position.y = absolutePositionY;
  18809. this.position.z = absolutePositionZ;
  18810. }
  18811. return this;
  18812. };
  18813. /**
  18814. * Sets the mesh position in its local space.
  18815. * Returns the TransformNode.
  18816. */
  18817. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18818. this.computeWorldMatrix();
  18819. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18820. return this;
  18821. };
  18822. /**
  18823. * Returns the mesh position in the local space from the current World matrix values.
  18824. * Returns a new Vector3.
  18825. */
  18826. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18827. this.computeWorldMatrix();
  18828. var invLocalWorldMatrix = this._localWorld.clone();
  18829. invLocalWorldMatrix.invert();
  18830. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18831. };
  18832. /**
  18833. * Translates the mesh along the passed Vector3 in its local space.
  18834. * Returns the TransformNode.
  18835. */
  18836. TransformNode.prototype.locallyTranslate = function (vector3) {
  18837. this.computeWorldMatrix(true);
  18838. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18839. return this;
  18840. };
  18841. /**
  18842. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18843. * @param targetPoint the position (must be in same space as current mesh) to look at
  18844. * @param yawCor optional yaw (y-axis) correction in radians
  18845. * @param pitchCor optional pitch (x-axis) correction in radians
  18846. * @param rollCor optional roll (z-axis) correction in radians
  18847. * @param space the choosen space of the target
  18848. * @returns the TransformNode.
  18849. */
  18850. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18851. if (yawCor === void 0) { yawCor = 0; }
  18852. if (pitchCor === void 0) { pitchCor = 0; }
  18853. if (rollCor === void 0) { rollCor = 0; }
  18854. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18855. var dv = TransformNode._lookAtVectorCache;
  18856. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18857. targetPoint.subtractToRef(pos, dv);
  18858. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18859. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18860. var pitch = Math.atan2(dv.y, len);
  18861. if (this.rotationQuaternion) {
  18862. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18863. }
  18864. else {
  18865. this.rotation.x = pitch + pitchCor;
  18866. this.rotation.y = yaw + yawCor;
  18867. this.rotation.z = rollCor;
  18868. }
  18869. return this;
  18870. };
  18871. /**
  18872. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18873. * This Vector3 is expressed in the World space.
  18874. */
  18875. TransformNode.prototype.getDirection = function (localAxis) {
  18876. var result = BABYLON.Vector3.Zero();
  18877. this.getDirectionToRef(localAxis, result);
  18878. return result;
  18879. };
  18880. /**
  18881. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18882. * localAxis is expressed in the mesh local space.
  18883. * result is computed in the Wordl space from the mesh World matrix.
  18884. * Returns the TransformNode.
  18885. */
  18886. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18887. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18888. return this;
  18889. };
  18890. /**
  18891. * Sets a new pivot point to the current node
  18892. * @param point defines the new pivot point to use
  18893. * @param space defines if the point is in world or local space (local by default)
  18894. * @returns the current TransformNode
  18895. */
  18896. TransformNode.prototype.setPivotPoint = function (point, space) {
  18897. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18898. if (this.getScene().getRenderId() == 0) {
  18899. this.computeWorldMatrix(true);
  18900. }
  18901. var wm = this.getWorldMatrix();
  18902. if (space == BABYLON.Space.WORLD) {
  18903. var tmat = BABYLON.Tmp.Matrix[0];
  18904. wm.invertToRef(tmat);
  18905. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18906. }
  18907. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18908. };
  18909. /**
  18910. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18911. */
  18912. TransformNode.prototype.getPivotPoint = function () {
  18913. var point = BABYLON.Vector3.Zero();
  18914. this.getPivotPointToRef(point);
  18915. return point;
  18916. };
  18917. /**
  18918. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18919. * Returns the TransformNode.
  18920. */
  18921. TransformNode.prototype.getPivotPointToRef = function (result) {
  18922. result.x = -this._pivotMatrix.m[12];
  18923. result.y = -this._pivotMatrix.m[13];
  18924. result.z = -this._pivotMatrix.m[14];
  18925. return this;
  18926. };
  18927. /**
  18928. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18929. */
  18930. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18931. var point = BABYLON.Vector3.Zero();
  18932. this.getAbsolutePivotPointToRef(point);
  18933. return point;
  18934. };
  18935. /**
  18936. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18937. * Returns the TransformNode.
  18938. */
  18939. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18940. result.x = this._pivotMatrix.m[12];
  18941. result.y = this._pivotMatrix.m[13];
  18942. result.z = this._pivotMatrix.m[14];
  18943. this.getPivotPointToRef(result);
  18944. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18945. return this;
  18946. };
  18947. /**
  18948. * Defines the passed node as the parent of the current node.
  18949. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18950. * Returns the TransformNode.
  18951. */
  18952. TransformNode.prototype.setParent = function (node) {
  18953. if (node === null) {
  18954. var rotation = BABYLON.Tmp.Quaternion[0];
  18955. var position = BABYLON.Tmp.Vector3[0];
  18956. var scale = BABYLON.Tmp.Vector3[1];
  18957. if (this.parent && this.parent.computeWorldMatrix) {
  18958. this.parent.computeWorldMatrix(true);
  18959. }
  18960. this.computeWorldMatrix(true);
  18961. this.getWorldMatrix().decompose(scale, rotation, position);
  18962. if (this.rotationQuaternion) {
  18963. this.rotationQuaternion.copyFrom(rotation);
  18964. }
  18965. else {
  18966. rotation.toEulerAnglesToRef(this.rotation);
  18967. }
  18968. this.scaling.x = scale.x;
  18969. this.scaling.y = scale.y;
  18970. this.scaling.z = scale.z;
  18971. this.position.x = position.x;
  18972. this.position.y = position.y;
  18973. this.position.z = position.z;
  18974. }
  18975. else {
  18976. var rotation = BABYLON.Tmp.Quaternion[0];
  18977. var position = BABYLON.Tmp.Vector3[0];
  18978. var scale = BABYLON.Tmp.Vector3[1];
  18979. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18980. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18981. this.computeWorldMatrix(true);
  18982. node.computeWorldMatrix(true);
  18983. node.getWorldMatrix().invertToRef(invParentMatrix);
  18984. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18985. diffMatrix.decompose(scale, rotation, position);
  18986. if (this.rotationQuaternion) {
  18987. this.rotationQuaternion.copyFrom(rotation);
  18988. }
  18989. else {
  18990. rotation.toEulerAnglesToRef(this.rotation);
  18991. }
  18992. this.position.x = position.x;
  18993. this.position.y = position.y;
  18994. this.position.z = position.z;
  18995. this.scaling.x = scale.x;
  18996. this.scaling.y = scale.y;
  18997. this.scaling.z = scale.z;
  18998. }
  18999. this.parent = node;
  19000. return this;
  19001. };
  19002. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19003. get: function () {
  19004. return this._nonUniformScaling;
  19005. },
  19006. enumerable: true,
  19007. configurable: true
  19008. });
  19009. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19010. if (this._nonUniformScaling === value) {
  19011. return false;
  19012. }
  19013. this._nonUniformScaling = value;
  19014. return true;
  19015. };
  19016. /**
  19017. * Attach the current TransformNode to another TransformNode associated with a bone
  19018. * @param bone Bone affecting the TransformNode
  19019. * @param affectedTransformNode TransformNode associated with the bone
  19020. */
  19021. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19022. this._transformToBoneReferal = affectedTransformNode;
  19023. this.parent = bone;
  19024. if (bone.getWorldMatrix().determinant() < 0) {
  19025. this.scalingDeterminant *= -1;
  19026. }
  19027. return this;
  19028. };
  19029. TransformNode.prototype.detachFromBone = function () {
  19030. if (!this.parent) {
  19031. return this;
  19032. }
  19033. if (this.parent.getWorldMatrix().determinant() < 0) {
  19034. this.scalingDeterminant *= -1;
  19035. }
  19036. this._transformToBoneReferal = null;
  19037. this.parent = null;
  19038. return this;
  19039. };
  19040. /**
  19041. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19042. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19043. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19044. * The passed axis is also normalized.
  19045. * Returns the TransformNode.
  19046. */
  19047. TransformNode.prototype.rotate = function (axis, amount, space) {
  19048. axis.normalize();
  19049. if (!this.rotationQuaternion) {
  19050. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19051. this.rotation = BABYLON.Vector3.Zero();
  19052. }
  19053. var rotationQuaternion;
  19054. if (!space || space === BABYLON.Space.LOCAL) {
  19055. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19056. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19057. }
  19058. else {
  19059. if (this.parent) {
  19060. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19061. invertParentWorldMatrix.invert();
  19062. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19063. }
  19064. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19065. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19066. }
  19067. return this;
  19068. };
  19069. /**
  19070. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19071. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19072. * The passed axis is also normalized.
  19073. * Returns the TransformNode.
  19074. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19075. */
  19076. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19077. axis.normalize();
  19078. if (!this.rotationQuaternion) {
  19079. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19080. this.rotation.copyFromFloats(0, 0, 0);
  19081. }
  19082. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19083. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19084. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19085. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19086. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19087. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19088. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19089. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19090. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19091. return this;
  19092. };
  19093. /**
  19094. * Translates the mesh along the axis vector for the passed distance in the given space.
  19095. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19096. * Returns the TransformNode.
  19097. */
  19098. TransformNode.prototype.translate = function (axis, distance, space) {
  19099. var displacementVector = axis.scale(distance);
  19100. if (!space || space === BABYLON.Space.LOCAL) {
  19101. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19102. this.setPositionWithLocalVector(tempV3);
  19103. }
  19104. else {
  19105. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19106. }
  19107. return this;
  19108. };
  19109. /**
  19110. * Adds a rotation step to the mesh current rotation.
  19111. * x, y, z are Euler angles expressed in radians.
  19112. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19113. * This means this rotation is made in the mesh local space only.
  19114. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19115. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19116. * ```javascript
  19117. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19118. * ```
  19119. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19120. * 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.
  19121. * Returns the TransformNode.
  19122. */
  19123. TransformNode.prototype.addRotation = function (x, y, z) {
  19124. var rotationQuaternion;
  19125. if (this.rotationQuaternion) {
  19126. rotationQuaternion = this.rotationQuaternion;
  19127. }
  19128. else {
  19129. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19130. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19131. }
  19132. var accumulation = BABYLON.Tmp.Quaternion[0];
  19133. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19134. rotationQuaternion.multiplyInPlace(accumulation);
  19135. if (!this.rotationQuaternion) {
  19136. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19137. }
  19138. return this;
  19139. };
  19140. /**
  19141. * Computes the mesh World matrix and returns it.
  19142. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19143. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19144. * If the parameter `force`is set to `true`, the actual computation is done.
  19145. * Returns the mesh World Matrix.
  19146. */
  19147. TransformNode.prototype.computeWorldMatrix = function (force) {
  19148. if (this._isWorldMatrixFrozen) {
  19149. return this._worldMatrix;
  19150. }
  19151. if (!force && this.isSynchronized(true)) {
  19152. this._currentRenderId = this.getScene().getRenderId();
  19153. return this._worldMatrix;
  19154. }
  19155. this._cache.position.copyFrom(this.position);
  19156. this._cache.scaling.copyFrom(this.scaling);
  19157. this._cache.pivotMatrixUpdated = false;
  19158. this._cache.billboardMode = this.billboardMode;
  19159. this._currentRenderId = this.getScene().getRenderId();
  19160. this._childRenderId = this.getScene().getRenderId();
  19161. this._isDirty = false;
  19162. // Scaling
  19163. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19164. // Rotation
  19165. //rotate, if quaternion is set and rotation was used
  19166. if (this.rotationQuaternion) {
  19167. var len = this.rotation.length();
  19168. if (len) {
  19169. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19170. this.rotation.copyFromFloats(0, 0, 0);
  19171. }
  19172. }
  19173. if (this.rotationQuaternion) {
  19174. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19175. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19176. }
  19177. else {
  19178. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19179. this._cache.rotation.copyFrom(this.rotation);
  19180. }
  19181. // Translation
  19182. var camera = this.getScene().activeCamera;
  19183. if (this.infiniteDistance && !this.parent && camera) {
  19184. var cameraWorldMatrix = camera.getWorldMatrix();
  19185. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19186. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19187. }
  19188. else {
  19189. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19190. }
  19191. // Composing transformations
  19192. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19193. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19194. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19195. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19196. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19197. // Need to decompose each rotation here
  19198. var currentPosition = BABYLON.Tmp.Vector3[3];
  19199. if (this.parent && this.parent.getWorldMatrix) {
  19200. if (this._transformToBoneReferal) {
  19201. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19202. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19203. }
  19204. else {
  19205. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19206. }
  19207. }
  19208. else {
  19209. currentPosition.copyFrom(this.position);
  19210. }
  19211. currentPosition.subtractInPlace(camera.globalPosition);
  19212. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19213. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19214. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19215. }
  19216. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19217. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19218. }
  19219. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19220. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19221. }
  19222. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19223. }
  19224. else {
  19225. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19226. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19227. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19228. }
  19229. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19230. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19231. }
  19232. // Local world
  19233. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19234. // Parent
  19235. if (this.parent && this.parent.getWorldMatrix) {
  19236. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19237. if (this._transformToBoneReferal) {
  19238. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19239. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19240. }
  19241. else {
  19242. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19243. }
  19244. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19245. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19246. this._worldMatrix.copyFrom(this._localWorld);
  19247. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19248. }
  19249. else {
  19250. if (this._transformToBoneReferal) {
  19251. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19252. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19253. }
  19254. else {
  19255. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19256. }
  19257. }
  19258. this._markSyncedWithParent();
  19259. }
  19260. else {
  19261. this._worldMatrix.copyFrom(this._localWorld);
  19262. }
  19263. // Post multiply inverse of pivotMatrix
  19264. if (this._postMultiplyPivotMatrix) {
  19265. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19266. }
  19267. // Normal matrix
  19268. if (!this.ignoreNonUniformScaling) {
  19269. if (this.scaling.isNonUniform) {
  19270. this._updateNonUniformScalingState(true);
  19271. }
  19272. else if (this.parent && this.parent._nonUniformScaling) {
  19273. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19274. }
  19275. else {
  19276. this._updateNonUniformScalingState(false);
  19277. }
  19278. }
  19279. else {
  19280. this._updateNonUniformScalingState(false);
  19281. }
  19282. this._afterComputeWorldMatrix();
  19283. // Absolute position
  19284. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19285. // Callbacks
  19286. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19287. if (!this._poseMatrix) {
  19288. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19289. }
  19290. // Cache the determinant
  19291. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19292. return this._worldMatrix;
  19293. };
  19294. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19295. };
  19296. /**
  19297. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19298. * @param func: callback function to add
  19299. *
  19300. * Returns the TransformNode.
  19301. */
  19302. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19303. this.onAfterWorldMatrixUpdateObservable.add(func);
  19304. return this;
  19305. };
  19306. /**
  19307. * Removes a registered callback function.
  19308. * Returns the TransformNode.
  19309. */
  19310. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19311. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19312. return this;
  19313. };
  19314. /**
  19315. * Clone the current transform node
  19316. * Returns the new transform node
  19317. * @param name Name of the new clone
  19318. * @param newParent New parent for the clone
  19319. * @param doNotCloneChildren Do not clone children hierarchy
  19320. */
  19321. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19322. var _this = this;
  19323. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19324. result.name = name;
  19325. result.id = name;
  19326. if (newParent) {
  19327. result.parent = newParent;
  19328. }
  19329. if (!doNotCloneChildren) {
  19330. // Children
  19331. var directDescendants = this.getDescendants(true);
  19332. for (var index = 0; index < directDescendants.length; index++) {
  19333. var child = directDescendants[index];
  19334. if (child.clone) {
  19335. child.clone(name + "." + child.name, result);
  19336. }
  19337. }
  19338. }
  19339. return result;
  19340. };
  19341. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19342. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19343. serializationObject.type = this.getClassName();
  19344. // Parent
  19345. if (this.parent) {
  19346. serializationObject.parentId = this.parent.id;
  19347. }
  19348. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19349. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19350. }
  19351. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19352. serializationObject.isEnabled = this.isEnabled();
  19353. // Parent
  19354. if (this.parent) {
  19355. serializationObject.parentId = this.parent.id;
  19356. }
  19357. return serializationObject;
  19358. };
  19359. // Statics
  19360. /**
  19361. * Returns a new TransformNode object parsed from the source provided.
  19362. * The parameter `parsedMesh` is the source.
  19363. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19364. */
  19365. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19366. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19367. if (BABYLON.Tags) {
  19368. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19369. }
  19370. if (parsedTransformNode.localMatrix) {
  19371. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19372. }
  19373. else if (parsedTransformNode.pivotMatrix) {
  19374. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19375. }
  19376. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19377. // Parent
  19378. if (parsedTransformNode.parentId) {
  19379. transformNode._waitingParentId = parsedTransformNode.parentId;
  19380. }
  19381. return transformNode;
  19382. };
  19383. /**
  19384. * Releases resources associated with this transform node.
  19385. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19386. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19387. */
  19388. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19389. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19390. // Animations
  19391. this.getScene().stopAnimation(this);
  19392. // Remove from scene
  19393. this.getScene().removeTransformNode(this);
  19394. this.onAfterWorldMatrixUpdateObservable.clear();
  19395. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19396. };
  19397. // Statics
  19398. TransformNode.BILLBOARDMODE_NONE = 0;
  19399. TransformNode.BILLBOARDMODE_X = 1;
  19400. TransformNode.BILLBOARDMODE_Y = 2;
  19401. TransformNode.BILLBOARDMODE_Z = 4;
  19402. TransformNode.BILLBOARDMODE_ALL = 7;
  19403. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19404. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19405. __decorate([
  19406. BABYLON.serializeAsVector3()
  19407. ], TransformNode.prototype, "_rotation", void 0);
  19408. __decorate([
  19409. BABYLON.serializeAsQuaternion()
  19410. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19411. __decorate([
  19412. BABYLON.serializeAsVector3()
  19413. ], TransformNode.prototype, "_scaling", void 0);
  19414. __decorate([
  19415. BABYLON.serialize()
  19416. ], TransformNode.prototype, "billboardMode", void 0);
  19417. __decorate([
  19418. BABYLON.serialize()
  19419. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19420. __decorate([
  19421. BABYLON.serialize()
  19422. ], TransformNode.prototype, "infiniteDistance", void 0);
  19423. __decorate([
  19424. BABYLON.serialize()
  19425. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19426. __decorate([
  19427. BABYLON.serializeAsVector3()
  19428. ], TransformNode.prototype, "position", void 0);
  19429. return TransformNode;
  19430. }(BABYLON.Node));
  19431. BABYLON.TransformNode = TransformNode;
  19432. })(BABYLON || (BABYLON = {}));
  19433. //# sourceMappingURL=babylon.transformNode.js.map
  19434. var BABYLON;
  19435. (function (BABYLON) {
  19436. /**
  19437. * Class used to store all common mesh properties
  19438. */
  19439. var AbstractMesh = /** @class */ (function (_super) {
  19440. __extends(AbstractMesh, _super);
  19441. // Constructor
  19442. /**
  19443. * Creates a new AbstractMesh
  19444. * @param name defines the name of the mesh
  19445. * @param scene defines the hosting scene
  19446. */
  19447. function AbstractMesh(name, scene) {
  19448. if (scene === void 0) { scene = null; }
  19449. var _this = _super.call(this, name, scene, false) || this;
  19450. _this._facetNb = 0; // facet number
  19451. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19452. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19453. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19454. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19455. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19456. _this._subDiv = {
  19457. max: 1,
  19458. X: 1,
  19459. Y: 1,
  19460. Z: 1
  19461. };
  19462. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19463. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19464. // Events
  19465. /**
  19466. * An event triggered when this mesh collides with another one
  19467. */
  19468. _this.onCollideObservable = new BABYLON.Observable();
  19469. /**
  19470. * An event triggered when the collision's position changes
  19471. */
  19472. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19473. /**
  19474. * An event triggered when material is changed
  19475. */
  19476. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19477. // Properties
  19478. /**
  19479. * Gets or sets the orientation for POV movement & rotation
  19480. */
  19481. _this.definedFacingForward = true;
  19482. /**
  19483. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19484. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19485. * * 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.
  19486. * @see http://doc.babylonjs.com/features/occlusionquery
  19487. */
  19488. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19489. /**
  19490. * 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:
  19491. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19492. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19493. * * 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.
  19494. * @see http://doc.babylonjs.com/features/occlusionquery
  19495. */
  19496. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19497. /**
  19498. * 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.
  19499. * The default value is -1 which means don't break the query and wait till the result
  19500. * @see http://doc.babylonjs.com/features/occlusionquery
  19501. */
  19502. _this.occlusionRetryCount = -1;
  19503. _this._occlusionInternalRetryCounter = 0;
  19504. _this._isOccluded = false;
  19505. _this._isOcclusionQueryInProgress = false;
  19506. _this._visibility = 1.0;
  19507. /** Gets or sets the alpha index used to sort transparent meshes
  19508. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19509. */
  19510. _this.alphaIndex = Number.MAX_VALUE;
  19511. /**
  19512. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19513. */
  19514. _this.isVisible = true;
  19515. /**
  19516. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19517. */
  19518. _this.isPickable = true;
  19519. /**
  19520. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19521. */
  19522. _this.showBoundingBox = false;
  19523. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19524. _this.showSubMeshesBoundingBox = false;
  19525. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19526. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19527. */
  19528. _this.isBlocker = false;
  19529. /**
  19530. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19531. */
  19532. _this.enablePointerMoveEvents = false;
  19533. /**
  19534. * Specifies the rendering group id for this mesh (0 by default)
  19535. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19536. */
  19537. _this.renderingGroupId = 0;
  19538. _this._receiveShadows = false;
  19539. /**
  19540. * Gets or sets a boolean indicating if the outline must be rendered as well
  19541. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19542. */
  19543. _this.renderOutline = false;
  19544. /** Defines color to use when rendering outline */
  19545. _this.outlineColor = BABYLON.Color3.Red();
  19546. /** Define width to use when rendering outline */
  19547. _this.outlineWidth = 0.02;
  19548. /**
  19549. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19550. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19551. */
  19552. _this.renderOverlay = false;
  19553. /** Defines color to use when rendering overlay */
  19554. _this.overlayColor = BABYLON.Color3.Red();
  19555. /** Defines alpha to use when rendering overlay */
  19556. _this.overlayAlpha = 0.5;
  19557. _this._hasVertexAlpha = false;
  19558. _this._useVertexColors = true;
  19559. _this._computeBonesUsingShaders = true;
  19560. _this._numBoneInfluencers = 4;
  19561. _this._applyFog = true;
  19562. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19563. _this.useOctreeForRenderingSelection = true;
  19564. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19565. _this.useOctreeForPicking = true;
  19566. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19567. _this.useOctreeForCollisions = true;
  19568. _this._layerMask = 0x0FFFFFFF;
  19569. /**
  19570. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19571. */
  19572. _this.alwaysSelectAsActiveMesh = false;
  19573. /**
  19574. * Gets or sets the current action manager
  19575. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19576. */
  19577. _this.actionManager = null;
  19578. /**
  19579. * Gets or sets impostor used for physic simulation
  19580. * @see http://doc.babylonjs.com/features/physics_engine
  19581. */
  19582. _this.physicsImpostor = null;
  19583. // Collisions
  19584. _this._checkCollisions = false;
  19585. _this._collisionMask = -1;
  19586. _this._collisionGroup = -1;
  19587. /**
  19588. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19589. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19590. */
  19591. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19592. /**
  19593. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19594. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19595. */
  19596. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19597. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19598. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19599. // Edges
  19600. /**
  19601. * Defines edge width used when edgesRenderer is enabled
  19602. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19603. */
  19604. _this.edgesWidth = 1;
  19605. /**
  19606. * Defines edge color used when edgesRenderer is enabled
  19607. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19608. */
  19609. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19610. // Cache
  19611. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19612. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19613. /** @hidden */
  19614. _this._renderId = 0;
  19615. /** @hidden */
  19616. _this._intersectionsInProgress = new Array();
  19617. /** @hidden */
  19618. _this._unIndexed = false;
  19619. /** @hidden */
  19620. _this._lightSources = new Array();
  19621. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19622. if (collidedMesh === void 0) { collidedMesh = null; }
  19623. //TODO move this to the collision coordinator!
  19624. if (_this.getScene().workerCollisions)
  19625. newPosition.multiplyInPlace(_this._collider._radius);
  19626. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19627. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19628. _this.position.addInPlace(_this._diffPositionForCollisions);
  19629. }
  19630. if (collidedMesh) {
  19631. _this.onCollideObservable.notifyObservers(collidedMesh);
  19632. }
  19633. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19634. };
  19635. _this.getScene().addMesh(_this);
  19636. _this._resyncLightSources();
  19637. return _this;
  19638. }
  19639. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19640. /**
  19641. * No billboard
  19642. */
  19643. get: function () {
  19644. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19645. },
  19646. enumerable: true,
  19647. configurable: true
  19648. });
  19649. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19650. /** Billboard on X axis */
  19651. get: function () {
  19652. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19653. },
  19654. enumerable: true,
  19655. configurable: true
  19656. });
  19657. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19658. /** Billboard on Y axis */
  19659. get: function () {
  19660. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19666. /** Billboard on Z axis */
  19667. get: function () {
  19668. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19674. /** Billboard on all axes */
  19675. get: function () {
  19676. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19677. },
  19678. enumerable: true,
  19679. configurable: true
  19680. });
  19681. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19682. /**
  19683. * Gets the number of facets in the mesh
  19684. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19685. */
  19686. get: function () {
  19687. return this._facetNb;
  19688. },
  19689. enumerable: true,
  19690. configurable: true
  19691. });
  19692. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19693. /**
  19694. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19695. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19696. */
  19697. get: function () {
  19698. return this._partitioningSubdivisions;
  19699. },
  19700. set: function (nb) {
  19701. this._partitioningSubdivisions = nb;
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19707. /**
  19708. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19709. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19710. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19711. */
  19712. get: function () {
  19713. return this._partitioningBBoxRatio;
  19714. },
  19715. set: function (ratio) {
  19716. this._partitioningBBoxRatio = ratio;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19722. /**
  19723. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19724. * Works only for updatable meshes.
  19725. * Doesn't work with multi-materials
  19726. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19727. */
  19728. get: function () {
  19729. return this._facetDepthSort;
  19730. },
  19731. set: function (sort) {
  19732. this._facetDepthSort = sort;
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19738. /**
  19739. * The location (Vector3) where the facet depth sort must be computed from.
  19740. * By default, the active camera position.
  19741. * Used only when facet depth sort is enabled
  19742. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19743. */
  19744. get: function () {
  19745. return this._facetDepthSortFrom;
  19746. },
  19747. set: function (location) {
  19748. this._facetDepthSortFrom = location;
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19754. /**
  19755. * gets a boolean indicating if facetData is enabled
  19756. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19757. */
  19758. get: function () {
  19759. return this._facetDataEnabled;
  19760. },
  19761. enumerable: true,
  19762. configurable: true
  19763. });
  19764. /** @hidden */
  19765. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19766. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19767. return false;
  19768. }
  19769. this._markSubMeshesAsMiscDirty();
  19770. return true;
  19771. };
  19772. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19773. /** Set a function to call when this mesh collides with another one */
  19774. set: function (callback) {
  19775. if (this._onCollideObserver) {
  19776. this.onCollideObservable.remove(this._onCollideObserver);
  19777. }
  19778. this._onCollideObserver = this.onCollideObservable.add(callback);
  19779. },
  19780. enumerable: true,
  19781. configurable: true
  19782. });
  19783. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19784. /** Set a function to call when the collision's position changes */
  19785. set: function (callback) {
  19786. if (this._onCollisionPositionChangeObserver) {
  19787. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19788. }
  19789. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19795. /**
  19796. * 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
  19797. * @see http://doc.babylonjs.com/features/occlusionquery
  19798. */
  19799. get: function () {
  19800. return this._isOccluded;
  19801. },
  19802. set: function (value) {
  19803. this._isOccluded = value;
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19809. /**
  19810. * Flag to check the progress status of the query
  19811. * @see http://doc.babylonjs.com/features/occlusionquery
  19812. */
  19813. get: function () {
  19814. return this._isOcclusionQueryInProgress;
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19820. /**
  19821. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19822. */
  19823. get: function () {
  19824. return this._visibility;
  19825. },
  19826. /**
  19827. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19828. */
  19829. set: function (value) {
  19830. if (this._visibility === value) {
  19831. return;
  19832. }
  19833. this._visibility = value;
  19834. this._markSubMeshesAsMiscDirty();
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "material", {
  19840. /** Gets or sets current material */
  19841. get: function () {
  19842. return this._material;
  19843. },
  19844. set: function (value) {
  19845. if (this._material === value) {
  19846. return;
  19847. }
  19848. this._material = value;
  19849. if (this.onMaterialChangedObservable.hasObservers) {
  19850. this.onMaterialChangedObservable.notifyObservers(this);
  19851. }
  19852. if (!this.subMeshes) {
  19853. return;
  19854. }
  19855. this._unBindEffect();
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19861. /**
  19862. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19863. * @see http://doc.babylonjs.com/babylon101/shadows
  19864. */
  19865. get: function () {
  19866. return this._receiveShadows;
  19867. },
  19868. set: function (value) {
  19869. if (this._receiveShadows === value) {
  19870. return;
  19871. }
  19872. this._receiveShadows = value;
  19873. this._markSubMeshesAsLightDirty();
  19874. },
  19875. enumerable: true,
  19876. configurable: true
  19877. });
  19878. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19879. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19880. get: function () {
  19881. return this._hasVertexAlpha;
  19882. },
  19883. set: function (value) {
  19884. if (this._hasVertexAlpha === value) {
  19885. return;
  19886. }
  19887. this._hasVertexAlpha = value;
  19888. this._markSubMeshesAsAttributesDirty();
  19889. this._markSubMeshesAsMiscDirty();
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19895. /** 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) */
  19896. get: function () {
  19897. return this._useVertexColors;
  19898. },
  19899. set: function (value) {
  19900. if (this._useVertexColors === value) {
  19901. return;
  19902. }
  19903. this._useVertexColors = value;
  19904. this._markSubMeshesAsAttributesDirty();
  19905. },
  19906. enumerable: true,
  19907. configurable: true
  19908. });
  19909. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19910. /**
  19911. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19912. */
  19913. get: function () {
  19914. return this._computeBonesUsingShaders;
  19915. },
  19916. set: function (value) {
  19917. if (this._computeBonesUsingShaders === value) {
  19918. return;
  19919. }
  19920. this._computeBonesUsingShaders = value;
  19921. this._markSubMeshesAsAttributesDirty();
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19927. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19928. get: function () {
  19929. return this._numBoneInfluencers;
  19930. },
  19931. set: function (value) {
  19932. if (this._numBoneInfluencers === value) {
  19933. return;
  19934. }
  19935. this._numBoneInfluencers = value;
  19936. this._markSubMeshesAsAttributesDirty();
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19942. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19943. get: function () {
  19944. return this._applyFog;
  19945. },
  19946. set: function (value) {
  19947. if (this._applyFog === value) {
  19948. return;
  19949. }
  19950. this._applyFog = value;
  19951. this._markSubMeshesAsMiscDirty();
  19952. },
  19953. enumerable: true,
  19954. configurable: true
  19955. });
  19956. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19957. /**
  19958. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19959. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19960. */
  19961. get: function () {
  19962. return this._layerMask;
  19963. },
  19964. set: function (value) {
  19965. if (value === this._layerMask) {
  19966. return;
  19967. }
  19968. this._layerMask = value;
  19969. this._resyncLightSources();
  19970. },
  19971. enumerable: true,
  19972. configurable: true
  19973. });
  19974. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19975. /**
  19976. * Gets or sets a collision mask used to mask collisions (default is -1).
  19977. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19978. */
  19979. get: function () {
  19980. return this._collisionMask;
  19981. },
  19982. set: function (mask) {
  19983. this._collisionMask = !isNaN(mask) ? mask : -1;
  19984. },
  19985. enumerable: true,
  19986. configurable: true
  19987. });
  19988. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19989. /**
  19990. * Gets or sets the current collision group mask (-1 by default).
  19991. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19992. */
  19993. get: function () {
  19994. return this._collisionGroup;
  19995. },
  19996. set: function (mask) {
  19997. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20003. /** @hidden */
  20004. get: function () {
  20005. return null;
  20006. },
  20007. enumerable: true,
  20008. configurable: true
  20009. });
  20010. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20011. get: function () {
  20012. return this._skeleton;
  20013. },
  20014. /**
  20015. * Gets or sets a skeleton to apply skining transformations
  20016. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20017. */
  20018. set: function (value) {
  20019. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20020. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20021. }
  20022. if (value && value.needInitialSkinMatrix) {
  20023. value._registerMeshWithPoseMatrix(this);
  20024. }
  20025. this._skeleton = value;
  20026. if (!this._skeleton) {
  20027. this._bonesTransformMatrices = null;
  20028. }
  20029. this._markSubMeshesAsAttributesDirty();
  20030. },
  20031. enumerable: true,
  20032. configurable: true
  20033. });
  20034. /**
  20035. * Returns the string "AbstractMesh"
  20036. * @returns "AbstractMesh"
  20037. */
  20038. AbstractMesh.prototype.getClassName = function () {
  20039. return "AbstractMesh";
  20040. };
  20041. /**
  20042. * Gets a string representation of the current mesh
  20043. * @param fullDetails defines a boolean indicating if full details must be included
  20044. * @returns a string representation of the current mesh
  20045. */
  20046. AbstractMesh.prototype.toString = function (fullDetails) {
  20047. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20048. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20049. if (this._skeleton) {
  20050. ret += ", skeleton: " + this._skeleton.name;
  20051. }
  20052. if (fullDetails) {
  20053. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20054. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20055. }
  20056. return ret;
  20057. };
  20058. /** @hidden */
  20059. AbstractMesh.prototype._rebuild = function () {
  20060. if (this._occlusionQuery) {
  20061. this._occlusionQuery = null;
  20062. }
  20063. if (this._edgesRenderer) {
  20064. this._edgesRenderer._rebuild();
  20065. }
  20066. if (!this.subMeshes) {
  20067. return;
  20068. }
  20069. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20070. var subMesh = _a[_i];
  20071. subMesh._rebuild();
  20072. }
  20073. };
  20074. /** @hidden */
  20075. AbstractMesh.prototype._resyncLightSources = function () {
  20076. this._lightSources.length = 0;
  20077. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20078. var light = _a[_i];
  20079. if (!light.isEnabled()) {
  20080. continue;
  20081. }
  20082. if (light.canAffectMesh(this)) {
  20083. this._lightSources.push(light);
  20084. }
  20085. }
  20086. this._markSubMeshesAsLightDirty();
  20087. };
  20088. /** @hidden */
  20089. AbstractMesh.prototype._resyncLighSource = function (light) {
  20090. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20091. var index = this._lightSources.indexOf(light);
  20092. if (index === -1) {
  20093. if (!isIn) {
  20094. return;
  20095. }
  20096. this._lightSources.push(light);
  20097. }
  20098. else {
  20099. if (isIn) {
  20100. return;
  20101. }
  20102. this._lightSources.splice(index, 1);
  20103. }
  20104. this._markSubMeshesAsLightDirty();
  20105. };
  20106. /** @hidden */
  20107. AbstractMesh.prototype._unBindEffect = function () {
  20108. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20109. var subMesh = _a[_i];
  20110. subMesh.setEffect(null);
  20111. }
  20112. };
  20113. /** @hidden */
  20114. AbstractMesh.prototype._removeLightSource = function (light) {
  20115. var index = this._lightSources.indexOf(light);
  20116. if (index === -1) {
  20117. return;
  20118. }
  20119. this._lightSources.splice(index, 1);
  20120. this._markSubMeshesAsLightDirty();
  20121. };
  20122. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20123. if (!this.subMeshes) {
  20124. return;
  20125. }
  20126. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20127. var subMesh = _a[_i];
  20128. if (subMesh._materialDefines) {
  20129. func(subMesh._materialDefines);
  20130. }
  20131. }
  20132. };
  20133. /** @hidden */
  20134. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20135. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20136. };
  20137. /** @hidden */
  20138. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20139. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20140. };
  20141. /** @hidden */
  20142. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20143. if (!this.subMeshes) {
  20144. return;
  20145. }
  20146. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20147. var subMesh = _a[_i];
  20148. var material = subMesh.getMaterial();
  20149. if (material) {
  20150. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20151. }
  20152. }
  20153. };
  20154. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20155. /**
  20156. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20157. */
  20158. get: function () {
  20159. return this._scaling;
  20160. },
  20161. set: function (newScaling) {
  20162. this._scaling = newScaling;
  20163. if (this.physicsImpostor) {
  20164. this.physicsImpostor.forceUpdate();
  20165. }
  20166. },
  20167. enumerable: true,
  20168. configurable: true
  20169. });
  20170. // Methods
  20171. /**
  20172. * Disables the mesh edge rendering mode
  20173. * @returns the currentAbstractMesh
  20174. */
  20175. AbstractMesh.prototype.disableEdgesRendering = function () {
  20176. if (this._edgesRenderer) {
  20177. this._edgesRenderer.dispose();
  20178. this._edgesRenderer = null;
  20179. }
  20180. return this;
  20181. };
  20182. /**
  20183. * Enables the edge rendering mode on the mesh.
  20184. * This mode makes the mesh edges visible
  20185. * @param epsilon defines the maximal distance between two angles to detect a face
  20186. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20187. * @returns the currentAbstractMesh
  20188. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20189. */
  20190. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20191. if (epsilon === void 0) { epsilon = 0.95; }
  20192. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20193. this.disableEdgesRendering();
  20194. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20195. return this;
  20196. };
  20197. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20198. /**
  20199. * Gets the edgesRenderer associated with the mesh
  20200. */
  20201. get: function () {
  20202. return this._edgesRenderer;
  20203. },
  20204. enumerable: true,
  20205. configurable: true
  20206. });
  20207. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20208. /**
  20209. * Returns true if the mesh is blocked. Implemented by child classes
  20210. */
  20211. get: function () {
  20212. return false;
  20213. },
  20214. enumerable: true,
  20215. configurable: true
  20216. });
  20217. /**
  20218. * Returns the mesh itself by default. Implemented by child classes
  20219. * @param camera defines the camera to use to pick the right LOD level
  20220. * @returns the currentAbstractMesh
  20221. */
  20222. AbstractMesh.prototype.getLOD = function (camera) {
  20223. return this;
  20224. };
  20225. /**
  20226. * Returns 0 by default. Implemented by child classes
  20227. * @returns an integer
  20228. */
  20229. AbstractMesh.prototype.getTotalVertices = function () {
  20230. return 0;
  20231. };
  20232. /**
  20233. * Returns null by default. Implemented by child classes
  20234. * @returns null
  20235. */
  20236. AbstractMesh.prototype.getIndices = function () {
  20237. return null;
  20238. };
  20239. /**
  20240. * Returns the array of the requested vertex data kind. Implemented by child classes
  20241. * @param kind defines the vertex data kind to use
  20242. * @returns null
  20243. */
  20244. AbstractMesh.prototype.getVerticesData = function (kind) {
  20245. return null;
  20246. };
  20247. /**
  20248. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20249. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20250. * Note that a new underlying VertexBuffer object is created each call.
  20251. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20252. * @param kind defines vertex data kind:
  20253. * * BABYLON.VertexBuffer.PositionKind
  20254. * * BABYLON.VertexBuffer.UVKind
  20255. * * BABYLON.VertexBuffer.UV2Kind
  20256. * * BABYLON.VertexBuffer.UV3Kind
  20257. * * BABYLON.VertexBuffer.UV4Kind
  20258. * * BABYLON.VertexBuffer.UV5Kind
  20259. * * BABYLON.VertexBuffer.UV6Kind
  20260. * * BABYLON.VertexBuffer.ColorKind
  20261. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20262. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20263. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20264. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20265. * @param data defines the data source
  20266. * @param updatable defines if the data must be flagged as updatable (or static)
  20267. * @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
  20268. * @returns the current mesh
  20269. */
  20270. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20271. return this;
  20272. };
  20273. /**
  20274. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20275. * If the mesh has no geometry, it is simply returned as it is.
  20276. * @param kind defines vertex data kind:
  20277. * * BABYLON.VertexBuffer.PositionKind
  20278. * * BABYLON.VertexBuffer.UVKind
  20279. * * BABYLON.VertexBuffer.UV2Kind
  20280. * * BABYLON.VertexBuffer.UV3Kind
  20281. * * BABYLON.VertexBuffer.UV4Kind
  20282. * * BABYLON.VertexBuffer.UV5Kind
  20283. * * BABYLON.VertexBuffer.UV6Kind
  20284. * * BABYLON.VertexBuffer.ColorKind
  20285. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20286. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20287. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20288. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20289. * @param data defines the data source
  20290. * @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
  20291. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20292. * @returns the current mesh
  20293. */
  20294. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20295. return this;
  20296. };
  20297. /**
  20298. * Sets the mesh indices,
  20299. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20300. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20301. * @param totalVertices Defines the total number of vertices
  20302. * @returns the current mesh
  20303. */
  20304. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20305. return this;
  20306. };
  20307. /**
  20308. * Gets a boolean indicating if specific vertex data is present
  20309. * @param kind defines the vertex data kind to use
  20310. * @returns true is data kind is present
  20311. */
  20312. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20313. return false;
  20314. };
  20315. /**
  20316. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20317. * @returns a BoundingInfo
  20318. */
  20319. AbstractMesh.prototype.getBoundingInfo = function () {
  20320. if (this._masterMesh) {
  20321. return this._masterMesh.getBoundingInfo();
  20322. }
  20323. if (!this._boundingInfo) {
  20324. // this._boundingInfo is being created here
  20325. this._updateBoundingInfo();
  20326. }
  20327. // cannot be null.
  20328. return this._boundingInfo;
  20329. };
  20330. /**
  20331. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20332. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20333. * @returns the current mesh
  20334. */
  20335. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20336. if (includeDescendants === void 0) { includeDescendants = true; }
  20337. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20338. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20339. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20340. if (maxDimension === 0) {
  20341. return this;
  20342. }
  20343. var scale = 1 / maxDimension;
  20344. this.scaling.scaleInPlace(scale);
  20345. return this;
  20346. };
  20347. /**
  20348. * Overwrite the current bounding info
  20349. * @param boundingInfo defines the new bounding info
  20350. * @returns the current mesh
  20351. */
  20352. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20353. this._boundingInfo = boundingInfo;
  20354. return this;
  20355. };
  20356. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20357. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20358. get: function () {
  20359. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20360. },
  20361. enumerable: true,
  20362. configurable: true
  20363. });
  20364. /** @hidden */
  20365. AbstractMesh.prototype._preActivate = function () {
  20366. };
  20367. /** @hidden */
  20368. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20369. };
  20370. /** @hidden */
  20371. AbstractMesh.prototype._activate = function (renderId) {
  20372. this._renderId = renderId;
  20373. };
  20374. /**
  20375. * Gets the current world matrix
  20376. * @returns a Matrix
  20377. */
  20378. AbstractMesh.prototype.getWorldMatrix = function () {
  20379. if (this._masterMesh) {
  20380. return this._masterMesh.getWorldMatrix();
  20381. }
  20382. return _super.prototype.getWorldMatrix.call(this);
  20383. };
  20384. /** @hidden */
  20385. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20386. if (this._masterMesh) {
  20387. return this._masterMesh._getWorldMatrixDeterminant();
  20388. }
  20389. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20390. };
  20391. // ================================== Point of View Movement =================================
  20392. /**
  20393. * Perform relative position change from the point of view of behind the front of the mesh.
  20394. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20395. * Supports definition of mesh facing forward or backward
  20396. * @param amountRight defines the distance on the right axis
  20397. * @param amountUp defines the distance on the up axis
  20398. * @param amountForward defines the distance on the forward axis
  20399. * @returns the current mesh
  20400. */
  20401. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20402. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20403. return this;
  20404. };
  20405. /**
  20406. * Calculate relative position change from the point of view of behind the front of the mesh.
  20407. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20408. * Supports definition of mesh facing forward or backward
  20409. * @param amountRight defines the distance on the right axis
  20410. * @param amountUp defines the distance on the up axis
  20411. * @param amountForward defines the distance on the forward axis
  20412. * @returns the new displacement vector
  20413. */
  20414. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20415. var rotMatrix = new BABYLON.Matrix();
  20416. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20417. rotQuaternion.toRotationMatrix(rotMatrix);
  20418. var translationDelta = BABYLON.Vector3.Zero();
  20419. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20420. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20421. return translationDelta;
  20422. };
  20423. // ================================== Point of View Rotation =================================
  20424. /**
  20425. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20426. * Supports definition of mesh facing forward or backward
  20427. * @param flipBack defines the flip
  20428. * @param twirlClockwise defines the twirl
  20429. * @param tiltRight defines the tilt
  20430. * @returns the current mesh
  20431. */
  20432. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20433. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20434. return this;
  20435. };
  20436. /**
  20437. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20438. * Supports definition of mesh facing forward or backward.
  20439. * @param flipBack defines the flip
  20440. * @param twirlClockwise defines the twirl
  20441. * @param tiltRight defines the tilt
  20442. * @returns the new rotation vector
  20443. */
  20444. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20445. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20446. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20447. };
  20448. /**
  20449. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20450. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20451. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20452. * @returns the new bounding vectors
  20453. */
  20454. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20455. if (includeDescendants === void 0) { includeDescendants = true; }
  20456. if (predicate === void 0) { predicate = null; }
  20457. // Ensures that all world matrix will be recomputed.
  20458. this.getScene().incrementRenderId();
  20459. this.computeWorldMatrix(true);
  20460. var min;
  20461. var max;
  20462. var boundingInfo = this.getBoundingInfo();
  20463. if (!this.subMeshes) {
  20464. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20465. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20466. }
  20467. else {
  20468. min = boundingInfo.boundingBox.minimumWorld;
  20469. max = boundingInfo.boundingBox.maximumWorld;
  20470. }
  20471. if (includeDescendants) {
  20472. var descendants = this.getDescendants(false);
  20473. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20474. var descendant = descendants_1[_i];
  20475. var childMesh = descendant;
  20476. childMesh.computeWorldMatrix(true);
  20477. // Filters meshes based on custom predicate function.
  20478. if (predicate && !predicate(childMesh)) {
  20479. continue;
  20480. }
  20481. //make sure we have the needed params to get mix and max
  20482. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20483. continue;
  20484. }
  20485. var childBoundingInfo = childMesh.getBoundingInfo();
  20486. var boundingBox = childBoundingInfo.boundingBox;
  20487. var minBox = boundingBox.minimumWorld;
  20488. var maxBox = boundingBox.maximumWorld;
  20489. BABYLON.Tools.CheckExtends(minBox, min, max);
  20490. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20491. }
  20492. }
  20493. return {
  20494. min: min,
  20495. max: max
  20496. };
  20497. };
  20498. /** @hidden */
  20499. AbstractMesh.prototype._updateBoundingInfo = function () {
  20500. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20501. this._boundingInfo.update(this.worldMatrixFromCache);
  20502. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20503. return this;
  20504. };
  20505. /** @hidden */
  20506. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20507. if (!this.subMeshes) {
  20508. return this;
  20509. }
  20510. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20511. var subMesh = this.subMeshes[subIndex];
  20512. if (!subMesh.IsGlobal) {
  20513. subMesh.updateBoundingInfo(matrix);
  20514. }
  20515. }
  20516. return this;
  20517. };
  20518. /** @hidden */
  20519. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20520. // Bounding info
  20521. this._updateBoundingInfo();
  20522. };
  20523. /**
  20524. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20525. * A mesh is in the frustum if its bounding box intersects the frustum
  20526. * @param frustumPlanes defines the frustum to test
  20527. * @returns true if the mesh is in the frustum planes
  20528. */
  20529. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20530. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20531. };
  20532. /**
  20533. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20534. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20535. * @param frustumPlanes defines the frustum to test
  20536. * @returns true if the mesh is completely in the frustum planes
  20537. */
  20538. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20539. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20540. };
  20541. /**
  20542. * True if the mesh intersects another mesh or a SolidParticle object
  20543. * @param mesh defines a target mesh or SolidParticle to test
  20544. * @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)
  20545. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20546. * @returns true if there is an intersection
  20547. */
  20548. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20549. if (precise === void 0) { precise = false; }
  20550. if (!this._boundingInfo || !mesh._boundingInfo) {
  20551. return false;
  20552. }
  20553. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20554. return true;
  20555. }
  20556. if (includeDescendants) {
  20557. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20558. var child = _a[_i];
  20559. if (child.intersectsMesh(mesh, precise, true)) {
  20560. return true;
  20561. }
  20562. }
  20563. }
  20564. return false;
  20565. };
  20566. /**
  20567. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20568. * @param point defines the point to test
  20569. * @returns true if there is an intersection
  20570. */
  20571. AbstractMesh.prototype.intersectsPoint = function (point) {
  20572. if (!this._boundingInfo) {
  20573. return false;
  20574. }
  20575. return this._boundingInfo.intersectsPoint(point);
  20576. };
  20577. /**
  20578. * Gets the current physics impostor
  20579. * @see http://doc.babylonjs.com/features/physics_engine
  20580. * @returns a physics impostor or null
  20581. */
  20582. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20583. return this.physicsImpostor;
  20584. };
  20585. /**
  20586. * Gets the position of the current mesh in camera space
  20587. * @param camera defines the camera to use
  20588. * @returns a position
  20589. */
  20590. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20591. if (camera === void 0) { camera = null; }
  20592. if (!camera) {
  20593. camera = this.getScene().activeCamera;
  20594. }
  20595. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20596. };
  20597. /**
  20598. * Returns the distance from the mesh to the active camera
  20599. * @param camera defines the camera to use
  20600. * @returns the distance
  20601. */
  20602. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20603. if (camera === void 0) { camera = null; }
  20604. if (!camera) {
  20605. camera = this.getScene().activeCamera;
  20606. }
  20607. return this.absolutePosition.subtract(camera.position).length();
  20608. };
  20609. /**
  20610. * Apply a physic impulse to the mesh
  20611. * @param force defines the force to apply
  20612. * @param contactPoint defines where to apply the force
  20613. * @returns the current mesh
  20614. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20615. */
  20616. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20617. if (!this.physicsImpostor) {
  20618. return this;
  20619. }
  20620. this.physicsImpostor.applyImpulse(force, contactPoint);
  20621. return this;
  20622. };
  20623. /**
  20624. * Creates a physic joint between two meshes
  20625. * @param otherMesh defines the other mesh to use
  20626. * @param pivot1 defines the pivot to use on this mesh
  20627. * @param pivot2 defines the pivot to use on the other mesh
  20628. * @param options defines additional options (can be plugin dependent)
  20629. * @returns the current mesh
  20630. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20631. */
  20632. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20633. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20634. return this;
  20635. }
  20636. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20637. mainPivot: pivot1,
  20638. connectedPivot: pivot2,
  20639. nativeParams: options
  20640. });
  20641. return this;
  20642. };
  20643. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20644. // Collisions
  20645. /**
  20646. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20647. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20648. */
  20649. get: function () {
  20650. return this._checkCollisions;
  20651. },
  20652. set: function (collisionEnabled) {
  20653. this._checkCollisions = collisionEnabled;
  20654. if (this.getScene().workerCollisions) {
  20655. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20656. }
  20657. },
  20658. enumerable: true,
  20659. configurable: true
  20660. });
  20661. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20662. /**
  20663. * Gets Collider object used to compute collisions (not physics)
  20664. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20665. */
  20666. get: function () {
  20667. return this._collider;
  20668. },
  20669. enumerable: true,
  20670. configurable: true
  20671. });
  20672. /**
  20673. * Move the mesh using collision engine
  20674. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20675. * @param displacement defines the requested displacement vector
  20676. * @returns the current mesh
  20677. */
  20678. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20679. var globalPosition = this.getAbsolutePosition();
  20680. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20681. if (!this._collider) {
  20682. this._collider = new BABYLON.Collider();
  20683. }
  20684. this._collider._radius = this.ellipsoid;
  20685. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20686. return this;
  20687. };
  20688. // Submeshes octree
  20689. /**
  20690. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20691. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20692. * @param maxCapacity defines the maximum size of each block (64 by default)
  20693. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20694. * @returns the new octree
  20695. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20696. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20697. */
  20698. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20699. if (maxCapacity === void 0) { maxCapacity = 64; }
  20700. if (maxDepth === void 0) { maxDepth = 2; }
  20701. if (!this._submeshesOctree) {
  20702. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20703. }
  20704. this.computeWorldMatrix(true);
  20705. var boundingInfo = this.getBoundingInfo();
  20706. // Update octree
  20707. var bbox = boundingInfo.boundingBox;
  20708. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20709. return this._submeshesOctree;
  20710. };
  20711. // Collisions
  20712. /** @hidden */
  20713. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20714. this._generatePointsArray();
  20715. if (!this._positions) {
  20716. return this;
  20717. }
  20718. // Transformation
  20719. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20720. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20721. subMesh._lastColliderWorldVertices = [];
  20722. subMesh._trianglePlanes = [];
  20723. var start = subMesh.verticesStart;
  20724. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20725. for (var i = start; i < end; i++) {
  20726. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20727. }
  20728. }
  20729. // Collide
  20730. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20731. if (collider.collisionFound) {
  20732. collider.collidedMesh = this;
  20733. }
  20734. return this;
  20735. };
  20736. /** @hidden */
  20737. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20738. var subMeshes;
  20739. var len;
  20740. // Octrees
  20741. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20742. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20743. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20744. len = intersections.length;
  20745. subMeshes = intersections.data;
  20746. }
  20747. else {
  20748. subMeshes = this.subMeshes;
  20749. len = subMeshes.length;
  20750. }
  20751. for (var index = 0; index < len; index++) {
  20752. var subMesh = subMeshes[index];
  20753. // Bounding test
  20754. if (len > 1 && !subMesh._checkCollision(collider))
  20755. continue;
  20756. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20757. }
  20758. return this;
  20759. };
  20760. /** @hidden */
  20761. AbstractMesh.prototype._checkCollision = function (collider) {
  20762. // Bounding box test
  20763. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20764. return this;
  20765. // Transformation matrix
  20766. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20767. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20768. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20769. return this;
  20770. };
  20771. // Picking
  20772. /** @hidden */
  20773. AbstractMesh.prototype._generatePointsArray = function () {
  20774. return false;
  20775. };
  20776. /**
  20777. * Checks if the passed Ray intersects with the mesh
  20778. * @param ray defines the ray to use
  20779. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20780. * @returns the picking info
  20781. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20782. */
  20783. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20784. var pickingInfo = new BABYLON.PickingInfo();
  20785. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20786. return pickingInfo;
  20787. }
  20788. if (!this._generatePointsArray()) {
  20789. return pickingInfo;
  20790. }
  20791. var intersectInfo = null;
  20792. // Octrees
  20793. var subMeshes;
  20794. var len;
  20795. if (this._submeshesOctree && this.useOctreeForPicking) {
  20796. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20797. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20798. len = intersections.length;
  20799. subMeshes = intersections.data;
  20800. }
  20801. else {
  20802. subMeshes = this.subMeshes;
  20803. len = subMeshes.length;
  20804. }
  20805. for (var index = 0; index < len; index++) {
  20806. var subMesh = subMeshes[index];
  20807. // Bounding test
  20808. if (len > 1 && !subMesh.canIntersects(ray))
  20809. continue;
  20810. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20811. if (currentIntersectInfo) {
  20812. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20813. intersectInfo = currentIntersectInfo;
  20814. intersectInfo.subMeshId = index;
  20815. if (fastCheck) {
  20816. break;
  20817. }
  20818. }
  20819. }
  20820. }
  20821. if (intersectInfo) {
  20822. // Get picked point
  20823. var world = this.getWorldMatrix();
  20824. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20825. var direction = ray.direction.clone();
  20826. direction = direction.scale(intersectInfo.distance);
  20827. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20828. var pickedPoint = worldOrigin.add(worldDirection);
  20829. // Return result
  20830. pickingInfo.hit = true;
  20831. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20832. pickingInfo.pickedPoint = pickedPoint;
  20833. pickingInfo.pickedMesh = this;
  20834. pickingInfo.bu = intersectInfo.bu || 0;
  20835. pickingInfo.bv = intersectInfo.bv || 0;
  20836. pickingInfo.faceId = intersectInfo.faceId;
  20837. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20838. return pickingInfo;
  20839. }
  20840. return pickingInfo;
  20841. };
  20842. /**
  20843. * Clones the current mesh
  20844. * @param name defines the mesh name
  20845. * @param newParent defines the new mesh parent
  20846. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20847. * @returns the new mesh
  20848. */
  20849. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20850. return null;
  20851. };
  20852. /**
  20853. * Disposes all the submeshes of the current meshnp
  20854. * @returns the current mesh
  20855. */
  20856. AbstractMesh.prototype.releaseSubMeshes = function () {
  20857. if (this.subMeshes) {
  20858. while (this.subMeshes.length) {
  20859. this.subMeshes[0].dispose();
  20860. }
  20861. }
  20862. else {
  20863. this.subMeshes = new Array();
  20864. }
  20865. return this;
  20866. };
  20867. /**
  20868. * Releases resources associated with this abstract mesh.
  20869. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20870. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20871. */
  20872. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20873. var _this = this;
  20874. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20875. var index;
  20876. // Smart Array Retainers.
  20877. this.getScene().freeActiveMeshes();
  20878. this.getScene().freeRenderingGroups();
  20879. // Action manager
  20880. if (this.actionManager !== undefined && this.actionManager !== null) {
  20881. this.actionManager.dispose();
  20882. this.actionManager = null;
  20883. }
  20884. // Skeleton
  20885. this._skeleton = null;
  20886. // Physics
  20887. if (this.physicsImpostor) {
  20888. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20889. }
  20890. // Intersections in progress
  20891. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20892. var other = this._intersectionsInProgress[index];
  20893. var pos = other._intersectionsInProgress.indexOf(this);
  20894. other._intersectionsInProgress.splice(pos, 1);
  20895. }
  20896. this._intersectionsInProgress = [];
  20897. // Lights
  20898. var lights = this.getScene().lights;
  20899. lights.forEach(function (light) {
  20900. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20901. if (meshIndex !== -1) {
  20902. light.includedOnlyMeshes.splice(meshIndex, 1);
  20903. }
  20904. meshIndex = light.excludedMeshes.indexOf(_this);
  20905. if (meshIndex !== -1) {
  20906. light.excludedMeshes.splice(meshIndex, 1);
  20907. }
  20908. // Shadow generators
  20909. var generator = light.getShadowGenerator();
  20910. if (generator) {
  20911. var shadowMap = generator.getShadowMap();
  20912. if (shadowMap && shadowMap.renderList) {
  20913. meshIndex = shadowMap.renderList.indexOf(_this);
  20914. if (meshIndex !== -1) {
  20915. shadowMap.renderList.splice(meshIndex, 1);
  20916. }
  20917. }
  20918. }
  20919. });
  20920. // Edges
  20921. if (this._edgesRenderer) {
  20922. this._edgesRenderer.dispose();
  20923. this._edgesRenderer = null;
  20924. }
  20925. // SubMeshes
  20926. if (this.getClassName() !== "InstancedMesh") {
  20927. this.releaseSubMeshes();
  20928. }
  20929. // Octree
  20930. var sceneOctree = this.getScene().selectionOctree;
  20931. if (sceneOctree !== undefined && sceneOctree !== null) {
  20932. var index = sceneOctree.dynamicContent.indexOf(this);
  20933. if (index !== -1) {
  20934. sceneOctree.dynamicContent.splice(index, 1);
  20935. }
  20936. }
  20937. // Query
  20938. var engine = this.getScene().getEngine();
  20939. if (this._occlusionQuery) {
  20940. this._isOcclusionQueryInProgress = false;
  20941. engine.deleteQuery(this._occlusionQuery);
  20942. this._occlusionQuery = null;
  20943. }
  20944. // Engine
  20945. engine.wipeCaches();
  20946. // Remove from scene
  20947. this.getScene().removeMesh(this);
  20948. if (disposeMaterialAndTextures) {
  20949. if (this.material) {
  20950. this.material.dispose(false, true);
  20951. }
  20952. }
  20953. if (!doNotRecurse) {
  20954. // Particles
  20955. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20956. if (this.getScene().particleSystems[index].emitter === this) {
  20957. this.getScene().particleSystems[index].dispose();
  20958. index--;
  20959. }
  20960. }
  20961. }
  20962. // facet data
  20963. if (this._facetDataEnabled) {
  20964. this.disableFacetData();
  20965. }
  20966. this.onAfterWorldMatrixUpdateObservable.clear();
  20967. this.onCollideObservable.clear();
  20968. this.onCollisionPositionChangeObservable.clear();
  20969. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20970. };
  20971. /**
  20972. * Adds the passed mesh as a child to the current mesh
  20973. * @param mesh defines the child mesh
  20974. * @returns the current mesh
  20975. */
  20976. AbstractMesh.prototype.addChild = function (mesh) {
  20977. mesh.setParent(this);
  20978. return this;
  20979. };
  20980. /**
  20981. * Removes the passed mesh from the current mesh children list
  20982. * @param mesh defines the child mesh
  20983. * @returns the current mesh
  20984. */
  20985. AbstractMesh.prototype.removeChild = function (mesh) {
  20986. mesh.setParent(null);
  20987. return this;
  20988. };
  20989. // Facet data
  20990. /** @hidden */
  20991. AbstractMesh.prototype._initFacetData = function () {
  20992. if (!this._facetNormals) {
  20993. this._facetNormals = new Array();
  20994. }
  20995. if (!this._facetPositions) {
  20996. this._facetPositions = new Array();
  20997. }
  20998. if (!this._facetPartitioning) {
  20999. this._facetPartitioning = new Array();
  21000. }
  21001. this._facetNb = (this.getIndices().length / 3) | 0;
  21002. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21003. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21004. for (var f = 0; f < this._facetNb; f++) {
  21005. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21006. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21007. }
  21008. this._facetDataEnabled = true;
  21009. return this;
  21010. };
  21011. /**
  21012. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21013. * This method can be called within the render loop.
  21014. * 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
  21015. * @returns the current mesh
  21016. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21017. */
  21018. AbstractMesh.prototype.updateFacetData = function () {
  21019. if (!this._facetDataEnabled) {
  21020. this._initFacetData();
  21021. }
  21022. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21023. var indices = this.getIndices();
  21024. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21025. var bInfo = this.getBoundingInfo();
  21026. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21027. // init arrays, matrix and sort function on first call
  21028. this._facetDepthSortEnabled = true;
  21029. if (indices instanceof Uint16Array) {
  21030. this._depthSortedIndices = new Uint16Array(indices);
  21031. }
  21032. else if (indices instanceof Uint32Array) {
  21033. this._depthSortedIndices = new Uint32Array(indices);
  21034. }
  21035. else {
  21036. var needs32bits = false;
  21037. for (var i = 0; i < indices.length; i++) {
  21038. if (indices[i] > 65535) {
  21039. needs32bits = true;
  21040. break;
  21041. }
  21042. }
  21043. if (needs32bits) {
  21044. this._depthSortedIndices = new Uint32Array(indices);
  21045. }
  21046. else {
  21047. this._depthSortedIndices = new Uint16Array(indices);
  21048. }
  21049. }
  21050. this._facetDepthSortFunction = function (f1, f2) {
  21051. return (f2.sqDistance - f1.sqDistance);
  21052. };
  21053. if (!this._facetDepthSortFrom) {
  21054. var camera = this.getScene().activeCamera;
  21055. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21056. }
  21057. this._depthSortedFacets = [];
  21058. for (var f = 0; f < this._facetNb; f++) {
  21059. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21060. this._depthSortedFacets.push(depthSortedFacet);
  21061. }
  21062. this._invertedMatrix = BABYLON.Matrix.Identity();
  21063. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21064. }
  21065. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21066. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21067. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21068. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21069. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21070. this._subDiv.max = this._partitioningSubdivisions;
  21071. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21072. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21073. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21074. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21075. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21076. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21077. // set the parameters for ComputeNormals()
  21078. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21079. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21080. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21081. this._facetParameters.bInfo = bInfo;
  21082. this._facetParameters.bbSize = this._bbSize;
  21083. this._facetParameters.subDiv = this._subDiv;
  21084. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21085. this._facetParameters.depthSort = this._facetDepthSort;
  21086. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21087. this.computeWorldMatrix(true);
  21088. this._worldMatrix.invertToRef(this._invertedMatrix);
  21089. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21090. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21091. }
  21092. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21093. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21094. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21095. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21096. var l = (this._depthSortedIndices.length / 3) | 0;
  21097. for (var f = 0; f < l; f++) {
  21098. var sind = this._depthSortedFacets[f].ind;
  21099. this._depthSortedIndices[f * 3] = indices[sind];
  21100. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21101. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21102. }
  21103. this.updateIndices(this._depthSortedIndices);
  21104. }
  21105. return this;
  21106. };
  21107. /**
  21108. * Returns the facetLocalNormals array.
  21109. * The normals are expressed in the mesh local spac
  21110. * @returns an array of Vector3
  21111. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21112. */
  21113. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21114. if (!this._facetNormals) {
  21115. this.updateFacetData();
  21116. }
  21117. return this._facetNormals;
  21118. };
  21119. /**
  21120. * Returns the facetLocalPositions array.
  21121. * The facet positions are expressed in the mesh local space
  21122. * @returns an array of Vector3
  21123. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21124. */
  21125. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21126. if (!this._facetPositions) {
  21127. this.updateFacetData();
  21128. }
  21129. return this._facetPositions;
  21130. };
  21131. /**
  21132. * Returns the facetLocalPartioning array
  21133. * @returns an array of array of numbers
  21134. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21135. */
  21136. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21137. if (!this._facetPartitioning) {
  21138. this.updateFacetData();
  21139. }
  21140. return this._facetPartitioning;
  21141. };
  21142. /**
  21143. * Returns the i-th facet position in the world system.
  21144. * This method allocates a new Vector3 per call
  21145. * @param i defines the facet index
  21146. * @returns a new Vector3
  21147. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21148. */
  21149. AbstractMesh.prototype.getFacetPosition = function (i) {
  21150. var pos = BABYLON.Vector3.Zero();
  21151. this.getFacetPositionToRef(i, pos);
  21152. return pos;
  21153. };
  21154. /**
  21155. * Sets the reference Vector3 with the i-th facet position in the world system
  21156. * @param i defines the facet index
  21157. * @param ref defines the target vector
  21158. * @returns the current mesh
  21159. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21160. */
  21161. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21162. var localPos = (this.getFacetLocalPositions())[i];
  21163. var world = this.getWorldMatrix();
  21164. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21165. return this;
  21166. };
  21167. /**
  21168. * Returns the i-th facet normal in the world system.
  21169. * This method allocates a new Vector3 per call
  21170. * @param i defines the facet index
  21171. * @returns a new Vector3
  21172. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21173. */
  21174. AbstractMesh.prototype.getFacetNormal = function (i) {
  21175. var norm = BABYLON.Vector3.Zero();
  21176. this.getFacetNormalToRef(i, norm);
  21177. return norm;
  21178. };
  21179. /**
  21180. * Sets the reference Vector3 with the i-th facet normal in the world system
  21181. * @param i defines the facet index
  21182. * @param ref defines the target vector
  21183. * @returns the current mesh
  21184. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21185. */
  21186. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21187. var localNorm = (this.getFacetLocalNormals())[i];
  21188. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21189. return this;
  21190. };
  21191. /**
  21192. * 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)
  21193. * @param x defines x coordinate
  21194. * @param y defines y coordinate
  21195. * @param z defines z coordinate
  21196. * @returns the array of facet indexes
  21197. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21198. */
  21199. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21200. var bInfo = this.getBoundingInfo();
  21201. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21202. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21203. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21204. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21205. return null;
  21206. }
  21207. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21208. };
  21209. /**
  21210. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21211. * @param projected sets as the (x,y,z) world projection on the facet
  21212. * @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
  21213. * @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
  21214. * @param x defines x coordinate
  21215. * @param y defines y coordinate
  21216. * @param z defines z coordinate
  21217. * @returns the face index if found (or null instead)
  21218. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21219. */
  21220. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21221. if (checkFace === void 0) { checkFace = false; }
  21222. if (facing === void 0) { facing = true; }
  21223. var world = this.getWorldMatrix();
  21224. var invMat = BABYLON.Tmp.Matrix[5];
  21225. world.invertToRef(invMat);
  21226. var invVect = BABYLON.Tmp.Vector3[8];
  21227. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21228. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21229. if (projected) {
  21230. // tranform the local computed projected vector to world coordinates
  21231. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21232. }
  21233. return closest;
  21234. };
  21235. /**
  21236. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21237. * @param projected sets as the (x,y,z) local projection on the facet
  21238. * @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
  21239. * @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
  21240. * @param x defines x coordinate
  21241. * @param y defines y coordinate
  21242. * @param z defines z coordinate
  21243. * @returns the face index if found (or null instead)
  21244. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21245. */
  21246. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21247. if (checkFace === void 0) { checkFace = false; }
  21248. if (facing === void 0) { facing = true; }
  21249. var closest = null;
  21250. var tmpx = 0.0;
  21251. var tmpy = 0.0;
  21252. var tmpz = 0.0;
  21253. var d = 0.0; // tmp dot facet normal * facet position
  21254. var t0 = 0.0;
  21255. var projx = 0.0;
  21256. var projy = 0.0;
  21257. var projz = 0.0;
  21258. // Get all the facets in the same partitioning block than (x, y, z)
  21259. var facetPositions = this.getFacetLocalPositions();
  21260. var facetNormals = this.getFacetLocalNormals();
  21261. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21262. if (!facetsInBlock) {
  21263. return null;
  21264. }
  21265. // Get the closest facet to (x, y, z)
  21266. var shortest = Number.MAX_VALUE; // init distance vars
  21267. var tmpDistance = shortest;
  21268. var fib; // current facet in the block
  21269. var norm; // current facet normal
  21270. var p0; // current facet barycenter position
  21271. // loop on all the facets in the current partitioning block
  21272. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21273. fib = facetsInBlock[idx];
  21274. norm = facetNormals[fib];
  21275. p0 = facetPositions[fib];
  21276. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21277. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21278. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21279. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21280. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21281. projx = x + norm.x * t0;
  21282. projy = y + norm.y * t0;
  21283. projz = z + norm.z * t0;
  21284. tmpx = projx - x;
  21285. tmpy = projy - y;
  21286. tmpz = projz - z;
  21287. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21288. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21289. shortest = tmpDistance;
  21290. closest = fib;
  21291. if (projected) {
  21292. projected.x = projx;
  21293. projected.y = projy;
  21294. projected.z = projz;
  21295. }
  21296. }
  21297. }
  21298. }
  21299. return closest;
  21300. };
  21301. /**
  21302. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21303. * @returns the parameters
  21304. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21305. */
  21306. AbstractMesh.prototype.getFacetDataParameters = function () {
  21307. return this._facetParameters;
  21308. };
  21309. /**
  21310. * Disables the feature FacetData and frees the related memory
  21311. * @returns the current mesh
  21312. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21313. */
  21314. AbstractMesh.prototype.disableFacetData = function () {
  21315. if (this._facetDataEnabled) {
  21316. this._facetDataEnabled = false;
  21317. this._facetPositions = new Array();
  21318. this._facetNormals = new Array();
  21319. this._facetPartitioning = new Array();
  21320. this._facetParameters = null;
  21321. this._depthSortedIndices = new Uint32Array(0);
  21322. }
  21323. return this;
  21324. };
  21325. /**
  21326. * Updates the AbstractMesh indices array
  21327. * @param indices defines the data source
  21328. * @returns the current mesh
  21329. */
  21330. AbstractMesh.prototype.updateIndices = function (indices) {
  21331. return this;
  21332. };
  21333. /**
  21334. * Creates new normals data for the mesh
  21335. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21336. * @returns the current mesh
  21337. */
  21338. AbstractMesh.prototype.createNormals = function (updatable) {
  21339. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21340. var indices = this.getIndices();
  21341. var normals;
  21342. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21343. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21344. }
  21345. else {
  21346. normals = [];
  21347. }
  21348. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21349. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21350. return this;
  21351. };
  21352. /**
  21353. * Align the mesh with a normal
  21354. * @param normal defines the normal to use
  21355. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21356. * @returns the current mesh
  21357. */
  21358. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21359. if (!upDirection) {
  21360. upDirection = BABYLON.Axis.Y;
  21361. }
  21362. var axisX = BABYLON.Tmp.Vector3[0];
  21363. var axisZ = BABYLON.Tmp.Vector3[1];
  21364. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21365. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21366. if (this.rotationQuaternion) {
  21367. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21368. }
  21369. else {
  21370. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21371. }
  21372. return this;
  21373. };
  21374. /** @hidden */
  21375. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21376. var engine = this.getEngine();
  21377. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21378. this._isOccluded = false;
  21379. return;
  21380. }
  21381. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21382. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21383. if (isOcclusionQueryAvailable) {
  21384. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21385. this._isOcclusionQueryInProgress = false;
  21386. this._occlusionInternalRetryCounter = 0;
  21387. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21388. }
  21389. else {
  21390. this._occlusionInternalRetryCounter++;
  21391. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21392. this._isOcclusionQueryInProgress = false;
  21393. this._occlusionInternalRetryCounter = 0;
  21394. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21395. // if strict continue the last state of the object.
  21396. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21397. }
  21398. else {
  21399. return;
  21400. }
  21401. }
  21402. }
  21403. var scene = this.getScene();
  21404. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21405. if (!this._occlusionQuery) {
  21406. this._occlusionQuery = engine.createQuery();
  21407. }
  21408. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21409. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21410. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21411. this._isOcclusionQueryInProgress = true;
  21412. };
  21413. /** No occlusion */
  21414. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21415. /** Occlusion set to optimisitic */
  21416. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21417. /** Occlusion set to strict */
  21418. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21419. /** Use an accurante occlusion algorithm */
  21420. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21421. /** Use a conservative occlusion algorithm */
  21422. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21423. return AbstractMesh;
  21424. }(BABYLON.TransformNode));
  21425. BABYLON.AbstractMesh = AbstractMesh;
  21426. })(BABYLON || (BABYLON = {}));
  21427. //# sourceMappingURL=babylon.abstractMesh.js.map
  21428. var BABYLON;
  21429. (function (BABYLON) {
  21430. /**
  21431. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21432. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21433. * 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.
  21434. */
  21435. var Light = /** @class */ (function (_super) {
  21436. __extends(Light, _super);
  21437. /**
  21438. * Creates a Light object in the scene.
  21439. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21440. * @param name The firendly name of the light
  21441. * @param scene The scene the light belongs too
  21442. */
  21443. function Light(name, scene) {
  21444. var _this = _super.call(this, name, scene) || this;
  21445. /**
  21446. * Diffuse gives the basic color to an object.
  21447. */
  21448. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21449. /**
  21450. * Specular produces a highlight color on an object.
  21451. * Note: This is note affecting PBR materials.
  21452. */
  21453. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21454. /**
  21455. * Strength of the light.
  21456. * Note: By default it is define in the framework own unit.
  21457. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21458. */
  21459. _this.intensity = 1.0;
  21460. /**
  21461. * Defines how far from the source the light is impacting in scene units.
  21462. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21463. */
  21464. _this.range = Number.MAX_VALUE;
  21465. /**
  21466. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21467. * of light.
  21468. */
  21469. _this._photometricScale = 1.0;
  21470. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21471. _this._radius = 0.00001;
  21472. /**
  21473. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21474. * exceeding the number allowed of the materials.
  21475. */
  21476. _this.renderPriority = 0;
  21477. _this._shadowEnabled = true;
  21478. _this._excludeWithLayerMask = 0;
  21479. _this._includeOnlyWithLayerMask = 0;
  21480. _this._lightmapMode = 0;
  21481. /**
  21482. * @hidden Internal use only.
  21483. */
  21484. _this._excludedMeshesIds = new Array();
  21485. /**
  21486. * @hidden Internal use only.
  21487. */
  21488. _this._includedOnlyMeshesIds = new Array();
  21489. _this.getScene().addLight(_this);
  21490. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21491. _this._buildUniformLayout();
  21492. _this.includedOnlyMeshes = new Array();
  21493. _this.excludedMeshes = new Array();
  21494. _this._resyncMeshes();
  21495. return _this;
  21496. }
  21497. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21498. /**
  21499. * If every light affecting the material is in this lightmapMode,
  21500. * material.lightmapTexture adds or multiplies
  21501. * (depends on material.useLightmapAsShadowmap)
  21502. * after every other light calculations.
  21503. */
  21504. get: function () {
  21505. return Light._LIGHTMAP_DEFAULT;
  21506. },
  21507. enumerable: true,
  21508. configurable: true
  21509. });
  21510. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21511. /**
  21512. * material.lightmapTexture as only diffuse lighting from this light
  21513. * adds only specular lighting from this light
  21514. * adds dynamic shadows
  21515. */
  21516. get: function () {
  21517. return Light._LIGHTMAP_SPECULAR;
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21523. /**
  21524. * material.lightmapTexture as only lighting
  21525. * no light calculation from this light
  21526. * only adds dynamic shadows from this light
  21527. */
  21528. get: function () {
  21529. return Light._LIGHTMAP_SHADOWSONLY;
  21530. },
  21531. enumerable: true,
  21532. configurable: true
  21533. });
  21534. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21535. /**
  21536. * Each light type uses the default quantity according to its type:
  21537. * point/spot lights use luminous intensity
  21538. * directional lights use illuminance
  21539. */
  21540. get: function () {
  21541. return Light._INTENSITYMODE_AUTOMATIC;
  21542. },
  21543. enumerable: true,
  21544. configurable: true
  21545. });
  21546. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21547. /**
  21548. * lumen (lm)
  21549. */
  21550. get: function () {
  21551. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21552. },
  21553. enumerable: true,
  21554. configurable: true
  21555. });
  21556. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21557. /**
  21558. * candela (lm/sr)
  21559. */
  21560. get: function () {
  21561. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21562. },
  21563. enumerable: true,
  21564. configurable: true
  21565. });
  21566. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21567. /**
  21568. * lux (lm/m^2)
  21569. */
  21570. get: function () {
  21571. return Light._INTENSITYMODE_ILLUMINANCE;
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21577. /**
  21578. * nit (cd/m^2)
  21579. */
  21580. get: function () {
  21581. return Light._INTENSITYMODE_LUMINANCE;
  21582. },
  21583. enumerable: true,
  21584. configurable: true
  21585. });
  21586. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21587. /**
  21588. * Light type const id of the point light.
  21589. */
  21590. get: function () {
  21591. return Light._LIGHTTYPEID_POINTLIGHT;
  21592. },
  21593. enumerable: true,
  21594. configurable: true
  21595. });
  21596. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21597. /**
  21598. * Light type const id of the directional light.
  21599. */
  21600. get: function () {
  21601. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21607. /**
  21608. * Light type const id of the spot light.
  21609. */
  21610. get: function () {
  21611. return Light._LIGHTTYPEID_SPOTLIGHT;
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21617. /**
  21618. * Light type const id of the hemispheric light.
  21619. */
  21620. get: function () {
  21621. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Light.prototype, "intensityMode", {
  21627. /**
  21628. * Gets the photometric scale used to interpret the intensity.
  21629. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21630. */
  21631. get: function () {
  21632. return this._intensityMode;
  21633. },
  21634. /**
  21635. * Sets the photometric scale used to interpret the intensity.
  21636. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21637. */
  21638. set: function (value) {
  21639. this._intensityMode = value;
  21640. this._computePhotometricScale();
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. ;
  21646. ;
  21647. Object.defineProperty(Light.prototype, "radius", {
  21648. /**
  21649. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21650. */
  21651. get: function () {
  21652. return this._radius;
  21653. },
  21654. /**
  21655. * sets the light radius used by PBR Materials to simulate soft area lights.
  21656. */
  21657. set: function (value) {
  21658. this._radius = value;
  21659. this._computePhotometricScale();
  21660. },
  21661. enumerable: true,
  21662. configurable: true
  21663. });
  21664. ;
  21665. ;
  21666. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21667. /**
  21668. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21669. * the current shadow generator.
  21670. */
  21671. get: function () {
  21672. return this._shadowEnabled;
  21673. },
  21674. /**
  21675. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21676. * the current shadow generator.
  21677. */
  21678. set: function (value) {
  21679. if (this._shadowEnabled === value) {
  21680. return;
  21681. }
  21682. this._shadowEnabled = value;
  21683. this._markMeshesAsLightDirty();
  21684. },
  21685. enumerable: true,
  21686. configurable: true
  21687. });
  21688. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21689. /**
  21690. * Gets the only meshes impacted by this light.
  21691. */
  21692. get: function () {
  21693. return this._includedOnlyMeshes;
  21694. },
  21695. /**
  21696. * Sets the only meshes impacted by this light.
  21697. */
  21698. set: function (value) {
  21699. this._includedOnlyMeshes = value;
  21700. this._hookArrayForIncludedOnly(value);
  21701. },
  21702. enumerable: true,
  21703. configurable: true
  21704. });
  21705. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21706. /**
  21707. * Gets the meshes not impacted by this light.
  21708. */
  21709. get: function () {
  21710. return this._excludedMeshes;
  21711. },
  21712. /**
  21713. * Sets the meshes not impacted by this light.
  21714. */
  21715. set: function (value) {
  21716. this._excludedMeshes = value;
  21717. this._hookArrayForExcluded(value);
  21718. },
  21719. enumerable: true,
  21720. configurable: true
  21721. });
  21722. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21723. /**
  21724. * Gets the layer id use to find what meshes are not impacted by the light.
  21725. * Inactive if 0
  21726. */
  21727. get: function () {
  21728. return this._excludeWithLayerMask;
  21729. },
  21730. /**
  21731. * Sets the layer id use to find what meshes are not impacted by the light.
  21732. * Inactive if 0
  21733. */
  21734. set: function (value) {
  21735. this._excludeWithLayerMask = value;
  21736. this._resyncMeshes();
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21742. /**
  21743. * Gets the layer id use to find what meshes are impacted by the light.
  21744. * Inactive if 0
  21745. */
  21746. get: function () {
  21747. return this._includeOnlyWithLayerMask;
  21748. },
  21749. /**
  21750. * Sets the layer id use to find what meshes are impacted by the light.
  21751. * Inactive if 0
  21752. */
  21753. set: function (value) {
  21754. this._includeOnlyWithLayerMask = value;
  21755. this._resyncMeshes();
  21756. },
  21757. enumerable: true,
  21758. configurable: true
  21759. });
  21760. Object.defineProperty(Light.prototype, "lightmapMode", {
  21761. /**
  21762. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21763. */
  21764. get: function () {
  21765. return this._lightmapMode;
  21766. },
  21767. /**
  21768. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21769. */
  21770. set: function (value) {
  21771. if (this._lightmapMode === value) {
  21772. return;
  21773. }
  21774. this._lightmapMode = value;
  21775. this._markMeshesAsLightDirty();
  21776. },
  21777. enumerable: true,
  21778. configurable: true
  21779. });
  21780. /**
  21781. * Returns the string "Light".
  21782. * @returns the class name
  21783. */
  21784. Light.prototype.getClassName = function () {
  21785. return "Light";
  21786. };
  21787. /**
  21788. * Converts the light information to a readable string for debug purpose.
  21789. * @param fullDetails Supports for multiple levels of logging within scene loading
  21790. * @returns the human readable light info
  21791. */
  21792. Light.prototype.toString = function (fullDetails) {
  21793. var ret = "Name: " + this.name;
  21794. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21795. if (this.animations) {
  21796. for (var i = 0; i < this.animations.length; i++) {
  21797. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21798. }
  21799. }
  21800. if (fullDetails) {
  21801. }
  21802. return ret;
  21803. };
  21804. /**
  21805. * Set the enabled state of this node.
  21806. * @param value - the new enabled state
  21807. */
  21808. Light.prototype.setEnabled = function (value) {
  21809. _super.prototype.setEnabled.call(this, value);
  21810. this._resyncMeshes();
  21811. };
  21812. /**
  21813. * Returns the Light associated shadow generator if any.
  21814. * @return the associated shadow generator.
  21815. */
  21816. Light.prototype.getShadowGenerator = function () {
  21817. return this._shadowGenerator;
  21818. };
  21819. /**
  21820. * Returns a Vector3, the absolute light position in the World.
  21821. * @returns the world space position of the light
  21822. */
  21823. Light.prototype.getAbsolutePosition = function () {
  21824. return BABYLON.Vector3.Zero();
  21825. };
  21826. /**
  21827. * Specifies if the light will affect the passed mesh.
  21828. * @param mesh The mesh to test against the light
  21829. * @return true the mesh is affected otherwise, false.
  21830. */
  21831. Light.prototype.canAffectMesh = function (mesh) {
  21832. if (!mesh) {
  21833. return true;
  21834. }
  21835. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21836. return false;
  21837. }
  21838. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21839. return false;
  21840. }
  21841. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21842. return false;
  21843. }
  21844. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21845. return false;
  21846. }
  21847. return true;
  21848. };
  21849. /**
  21850. * Computes and Returns the light World matrix.
  21851. * @returns the world matrix
  21852. */
  21853. Light.prototype.getWorldMatrix = function () {
  21854. this._currentRenderId = this.getScene().getRenderId();
  21855. this._childRenderId = this._currentRenderId;
  21856. var worldMatrix = this._getWorldMatrix();
  21857. if (this.parent && this.parent.getWorldMatrix) {
  21858. if (!this._parentedWorldMatrix) {
  21859. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21860. }
  21861. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21862. this._markSyncedWithParent();
  21863. return this._parentedWorldMatrix;
  21864. }
  21865. return worldMatrix;
  21866. };
  21867. /**
  21868. * Sort function to order lights for rendering.
  21869. * @param a First Light object to compare to second.
  21870. * @param b Second Light object to compare first.
  21871. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21872. */
  21873. Light.CompareLightsPriority = function (a, b) {
  21874. //shadow-casting lights have priority over non-shadow-casting lights
  21875. //the renderPrioirty is a secondary sort criterion
  21876. if (a.shadowEnabled !== b.shadowEnabled) {
  21877. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21878. }
  21879. return b.renderPriority - a.renderPriority;
  21880. };
  21881. /**
  21882. * Releases resources associated with this node.
  21883. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21884. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21885. */
  21886. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21887. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21888. if (this._shadowGenerator) {
  21889. this._shadowGenerator.dispose();
  21890. this._shadowGenerator = null;
  21891. }
  21892. // Animations
  21893. this.getScene().stopAnimation(this);
  21894. // Remove from meshes
  21895. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21896. var mesh = _a[_i];
  21897. mesh._removeLightSource(this);
  21898. }
  21899. this._uniformBuffer.dispose();
  21900. // Remove from scene
  21901. this.getScene().removeLight(this);
  21902. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21903. };
  21904. /**
  21905. * Returns the light type ID (integer).
  21906. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21907. */
  21908. Light.prototype.getTypeID = function () {
  21909. return 0;
  21910. };
  21911. /**
  21912. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21913. * @returns the scaled intensity in intensity mode unit
  21914. */
  21915. Light.prototype.getScaledIntensity = function () {
  21916. return this._photometricScale * this.intensity;
  21917. };
  21918. /**
  21919. * Returns a new Light object, named "name", from the current one.
  21920. * @param name The name of the cloned light
  21921. * @returns the new created light
  21922. */
  21923. Light.prototype.clone = function (name) {
  21924. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21925. if (!constructor) {
  21926. return null;
  21927. }
  21928. return BABYLON.SerializationHelper.Clone(constructor, this);
  21929. };
  21930. /**
  21931. * Serializes the current light into a Serialization object.
  21932. * @returns the serialized object.
  21933. */
  21934. Light.prototype.serialize = function () {
  21935. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21936. // Type
  21937. serializationObject.type = this.getTypeID();
  21938. // Parent
  21939. if (this.parent) {
  21940. serializationObject.parentId = this.parent.id;
  21941. }
  21942. // Inclusion / exclusions
  21943. if (this.excludedMeshes.length > 0) {
  21944. serializationObject.excludedMeshesIds = [];
  21945. this.excludedMeshes.forEach(function (mesh) {
  21946. serializationObject.excludedMeshesIds.push(mesh.id);
  21947. });
  21948. }
  21949. if (this.includedOnlyMeshes.length > 0) {
  21950. serializationObject.includedOnlyMeshesIds = [];
  21951. this.includedOnlyMeshes.forEach(function (mesh) {
  21952. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21953. });
  21954. }
  21955. // Animations
  21956. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21957. serializationObject.ranges = this.serializeAnimationRanges();
  21958. return serializationObject;
  21959. };
  21960. /**
  21961. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21962. * This new light is named "name" and added to the passed scene.
  21963. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21964. * @param name The friendly name of the light
  21965. * @param scene The scene the new light will belong to
  21966. * @returns the constructor function
  21967. */
  21968. Light.GetConstructorFromName = function (type, name, scene) {
  21969. switch (type) {
  21970. case 0:
  21971. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21972. case 1:
  21973. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21974. case 2:
  21975. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21976. case 3:
  21977. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21978. }
  21979. return null;
  21980. };
  21981. /**
  21982. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21983. * @param parsedLight The JSON representation of the light
  21984. * @param scene The scene to create the parsed light in
  21985. * @returns the created light after parsing
  21986. */
  21987. Light.Parse = function (parsedLight, scene) {
  21988. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21989. if (!constructor) {
  21990. return null;
  21991. }
  21992. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21993. // Inclusion / exclusions
  21994. if (parsedLight.excludedMeshesIds) {
  21995. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21996. }
  21997. if (parsedLight.includedOnlyMeshesIds) {
  21998. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21999. }
  22000. // Parent
  22001. if (parsedLight.parentId) {
  22002. light._waitingParentId = parsedLight.parentId;
  22003. }
  22004. // Animations
  22005. if (parsedLight.animations) {
  22006. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22007. var parsedAnimation = parsedLight.animations[animationIndex];
  22008. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22009. }
  22010. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22011. }
  22012. if (parsedLight.autoAnimate) {
  22013. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22014. }
  22015. return light;
  22016. };
  22017. Light.prototype._hookArrayForExcluded = function (array) {
  22018. var _this = this;
  22019. var oldPush = array.push;
  22020. array.push = function () {
  22021. var items = [];
  22022. for (var _i = 0; _i < arguments.length; _i++) {
  22023. items[_i] = arguments[_i];
  22024. }
  22025. var result = oldPush.apply(array, items);
  22026. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22027. var item = items_1[_a];
  22028. item._resyncLighSource(_this);
  22029. }
  22030. return result;
  22031. };
  22032. var oldSplice = array.splice;
  22033. array.splice = function (index, deleteCount) {
  22034. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22035. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22036. var item = deleted_1[_i];
  22037. item._resyncLighSource(_this);
  22038. }
  22039. return deleted;
  22040. };
  22041. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22042. var item = array_1[_i];
  22043. item._resyncLighSource(this);
  22044. }
  22045. };
  22046. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22047. var _this = this;
  22048. var oldPush = array.push;
  22049. array.push = function () {
  22050. var items = [];
  22051. for (var _i = 0; _i < arguments.length; _i++) {
  22052. items[_i] = arguments[_i];
  22053. }
  22054. var result = oldPush.apply(array, items);
  22055. _this._resyncMeshes();
  22056. return result;
  22057. };
  22058. var oldSplice = array.splice;
  22059. array.splice = function (index, deleteCount) {
  22060. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22061. _this._resyncMeshes();
  22062. return deleted;
  22063. };
  22064. this._resyncMeshes();
  22065. };
  22066. Light.prototype._resyncMeshes = function () {
  22067. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22068. var mesh = _a[_i];
  22069. mesh._resyncLighSource(this);
  22070. }
  22071. };
  22072. /**
  22073. * Forces the meshes to update their light related information in their rendering used effects
  22074. * @hidden Internal Use Only
  22075. */
  22076. Light.prototype._markMeshesAsLightDirty = function () {
  22077. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22078. var mesh = _a[_i];
  22079. if (mesh._lightSources.indexOf(this) !== -1) {
  22080. mesh._markSubMeshesAsLightDirty();
  22081. }
  22082. }
  22083. };
  22084. /**
  22085. * Recomputes the cached photometric scale if needed.
  22086. */
  22087. Light.prototype._computePhotometricScale = function () {
  22088. this._photometricScale = this._getPhotometricScale();
  22089. this.getScene().resetCachedMaterial();
  22090. };
  22091. /**
  22092. * Returns the Photometric Scale according to the light type and intensity mode.
  22093. */
  22094. Light.prototype._getPhotometricScale = function () {
  22095. var photometricScale = 0.0;
  22096. var lightTypeID = this.getTypeID();
  22097. //get photometric mode
  22098. var photometricMode = this.intensityMode;
  22099. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22100. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22101. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22102. }
  22103. else {
  22104. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22105. }
  22106. }
  22107. //compute photometric scale
  22108. switch (lightTypeID) {
  22109. case Light.LIGHTTYPEID_POINTLIGHT:
  22110. case Light.LIGHTTYPEID_SPOTLIGHT:
  22111. switch (photometricMode) {
  22112. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22113. photometricScale = 1.0 / (4.0 * Math.PI);
  22114. break;
  22115. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22116. photometricScale = 1.0;
  22117. break;
  22118. case Light.INTENSITYMODE_LUMINANCE:
  22119. photometricScale = this.radius * this.radius;
  22120. break;
  22121. }
  22122. break;
  22123. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22124. switch (photometricMode) {
  22125. case Light.INTENSITYMODE_ILLUMINANCE:
  22126. photometricScale = 1.0;
  22127. break;
  22128. case Light.INTENSITYMODE_LUMINANCE:
  22129. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22130. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22131. var apexAngleRadians = this.radius;
  22132. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22133. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22134. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22135. photometricScale = solidAngle;
  22136. break;
  22137. }
  22138. break;
  22139. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22140. // No fall off in hemisperic light.
  22141. photometricScale = 1.0;
  22142. break;
  22143. }
  22144. return photometricScale;
  22145. };
  22146. /**
  22147. * Reorder the light in the scene according to their defined priority.
  22148. * @hidden Internal Use Only
  22149. */
  22150. Light.prototype._reorderLightsInScene = function () {
  22151. var scene = this.getScene();
  22152. if (this._renderPriority != 0) {
  22153. scene.requireLightSorting = true;
  22154. }
  22155. this.getScene().sortLightsByPriority();
  22156. };
  22157. //lightmapMode Consts
  22158. Light._LIGHTMAP_DEFAULT = 0;
  22159. Light._LIGHTMAP_SPECULAR = 1;
  22160. Light._LIGHTMAP_SHADOWSONLY = 2;
  22161. // Intensity Mode Consts
  22162. Light._INTENSITYMODE_AUTOMATIC = 0;
  22163. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22164. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22165. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22166. Light._INTENSITYMODE_LUMINANCE = 4;
  22167. // Light types ids const.
  22168. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22169. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22170. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22171. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22172. __decorate([
  22173. BABYLON.serializeAsColor3()
  22174. ], Light.prototype, "diffuse", void 0);
  22175. __decorate([
  22176. BABYLON.serializeAsColor3()
  22177. ], Light.prototype, "specular", void 0);
  22178. __decorate([
  22179. BABYLON.serialize()
  22180. ], Light.prototype, "intensity", void 0);
  22181. __decorate([
  22182. BABYLON.serialize()
  22183. ], Light.prototype, "range", void 0);
  22184. __decorate([
  22185. BABYLON.serialize()
  22186. ], Light.prototype, "intensityMode", null);
  22187. __decorate([
  22188. BABYLON.serialize()
  22189. ], Light.prototype, "radius", null);
  22190. __decorate([
  22191. BABYLON.serialize()
  22192. ], Light.prototype, "_renderPriority", void 0);
  22193. __decorate([
  22194. BABYLON.expandToProperty("_reorderLightsInScene")
  22195. ], Light.prototype, "renderPriority", void 0);
  22196. __decorate([
  22197. BABYLON.serialize("shadowEnabled")
  22198. ], Light.prototype, "_shadowEnabled", void 0);
  22199. __decorate([
  22200. BABYLON.serialize("excludeWithLayerMask")
  22201. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22202. __decorate([
  22203. BABYLON.serialize("includeOnlyWithLayerMask")
  22204. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22205. __decorate([
  22206. BABYLON.serialize("lightmapMode")
  22207. ], Light.prototype, "_lightmapMode", void 0);
  22208. return Light;
  22209. }(BABYLON.Node));
  22210. BABYLON.Light = Light;
  22211. })(BABYLON || (BABYLON = {}));
  22212. //# sourceMappingURL=babylon.light.js.map
  22213. var BABYLON;
  22214. (function (BABYLON) {
  22215. var Camera = /** @class */ (function (_super) {
  22216. __extends(Camera, _super);
  22217. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22218. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22219. var _this = _super.call(this, name, scene) || this;
  22220. /**
  22221. * The vector the camera should consider as up.
  22222. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22223. */
  22224. _this.upVector = BABYLON.Vector3.Up();
  22225. _this.orthoLeft = null;
  22226. _this.orthoRight = null;
  22227. _this.orthoBottom = null;
  22228. _this.orthoTop = null;
  22229. /**
  22230. * FOV is set in Radians. (default is 0.8)
  22231. */
  22232. _this.fov = 0.8;
  22233. _this.minZ = 1;
  22234. _this.maxZ = 10000.0;
  22235. _this.inertia = 0.9;
  22236. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22237. _this.isIntermediate = false;
  22238. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22239. /**
  22240. * Restricts the camera to viewing objects with the same layerMask.
  22241. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22242. */
  22243. _this.layerMask = 0x0FFFFFFF;
  22244. /**
  22245. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22246. */
  22247. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22248. // Camera rig members
  22249. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22250. _this._rigCameras = new Array();
  22251. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22252. _this._skipRendering = false;
  22253. _this.customRenderTargets = new Array();
  22254. // Observables
  22255. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22256. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22257. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22258. _this.onRestoreStateObservable = new BABYLON.Observable();
  22259. // Cache
  22260. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22261. _this._projectionMatrix = new BABYLON.Matrix();
  22262. _this._doNotComputeProjectionMatrix = false;
  22263. _this._worldMatrix = BABYLON.Matrix.Identity();
  22264. _this._postProcesses = new Array();
  22265. _this._transformMatrix = BABYLON.Matrix.Zero();
  22266. _this._activeMeshes = new BABYLON.SmartArray(256);
  22267. _this._globalPosition = BABYLON.Vector3.Zero();
  22268. _this._refreshFrustumPlanes = true;
  22269. _this.getScene().addCamera(_this);
  22270. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22271. _this.getScene().activeCamera = _this;
  22272. }
  22273. _this.position = position;
  22274. return _this;
  22275. }
  22276. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22277. get: function () {
  22278. return Camera._PERSPECTIVE_CAMERA;
  22279. },
  22280. enumerable: true,
  22281. configurable: true
  22282. });
  22283. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22284. get: function () {
  22285. return Camera._ORTHOGRAPHIC_CAMERA;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22291. /**
  22292. * This is the default FOV mode for perspective cameras.
  22293. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22294. *
  22295. */
  22296. get: function () {
  22297. return Camera._FOVMODE_VERTICAL_FIXED;
  22298. },
  22299. enumerable: true,
  22300. configurable: true
  22301. });
  22302. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22303. /**
  22304. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22305. *
  22306. */
  22307. get: function () {
  22308. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22309. },
  22310. enumerable: true,
  22311. configurable: true
  22312. });
  22313. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22314. get: function () {
  22315. return Camera._RIG_MODE_NONE;
  22316. },
  22317. enumerable: true,
  22318. configurable: true
  22319. });
  22320. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22321. get: function () {
  22322. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22323. },
  22324. enumerable: true,
  22325. configurable: true
  22326. });
  22327. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22328. get: function () {
  22329. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22330. },
  22331. enumerable: true,
  22332. configurable: true
  22333. });
  22334. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22335. get: function () {
  22336. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22337. },
  22338. enumerable: true,
  22339. configurable: true
  22340. });
  22341. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22342. get: function () {
  22343. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22344. },
  22345. enumerable: true,
  22346. configurable: true
  22347. });
  22348. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22349. get: function () {
  22350. return Camera._RIG_MODE_VR;
  22351. },
  22352. enumerable: true,
  22353. configurable: true
  22354. });
  22355. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22356. get: function () {
  22357. return Camera._RIG_MODE_WEBVR;
  22358. },
  22359. enumerable: true,
  22360. configurable: true
  22361. });
  22362. /**
  22363. * Store current camera state (fov, position, etc..)
  22364. */
  22365. Camera.prototype.storeState = function () {
  22366. this._stateStored = true;
  22367. this._storedFov = this.fov;
  22368. return this;
  22369. };
  22370. /**
  22371. * Restores the camera state values if it has been stored. You must call storeState() first
  22372. */
  22373. Camera.prototype._restoreStateValues = function () {
  22374. if (!this._stateStored) {
  22375. return false;
  22376. }
  22377. this.fov = this._storedFov;
  22378. return true;
  22379. };
  22380. /**
  22381. * Restored camera state. You must call storeState() first
  22382. */
  22383. Camera.prototype.restoreState = function () {
  22384. if (this._restoreStateValues()) {
  22385. this.onRestoreStateObservable.notifyObservers(this);
  22386. return true;
  22387. }
  22388. return false;
  22389. };
  22390. Camera.prototype.getClassName = function () {
  22391. return "Camera";
  22392. };
  22393. /**
  22394. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22395. */
  22396. Camera.prototype.toString = function (fullDetails) {
  22397. var ret = "Name: " + this.name;
  22398. ret += ", type: " + this.getClassName();
  22399. if (this.animations) {
  22400. for (var i = 0; i < this.animations.length; i++) {
  22401. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22402. }
  22403. }
  22404. if (fullDetails) {
  22405. }
  22406. return ret;
  22407. };
  22408. Object.defineProperty(Camera.prototype, "globalPosition", {
  22409. get: function () {
  22410. return this._globalPosition;
  22411. },
  22412. enumerable: true,
  22413. configurable: true
  22414. });
  22415. Camera.prototype.getActiveMeshes = function () {
  22416. return this._activeMeshes;
  22417. };
  22418. Camera.prototype.isActiveMesh = function (mesh) {
  22419. return (this._activeMeshes.indexOf(mesh) !== -1);
  22420. };
  22421. /**
  22422. * Is this camera ready to be used/rendered
  22423. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22424. * @return true if the camera is ready
  22425. */
  22426. Camera.prototype.isReady = function (completeCheck) {
  22427. if (completeCheck === void 0) { completeCheck = false; }
  22428. if (completeCheck) {
  22429. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22430. var pp = _a[_i];
  22431. if (pp && !pp.isReady()) {
  22432. return false;
  22433. }
  22434. }
  22435. }
  22436. return _super.prototype.isReady.call(this, completeCheck);
  22437. };
  22438. //Cache
  22439. Camera.prototype._initCache = function () {
  22440. _super.prototype._initCache.call(this);
  22441. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22442. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22443. this._cache.mode = undefined;
  22444. this._cache.minZ = undefined;
  22445. this._cache.maxZ = undefined;
  22446. this._cache.fov = undefined;
  22447. this._cache.fovMode = undefined;
  22448. this._cache.aspectRatio = undefined;
  22449. this._cache.orthoLeft = undefined;
  22450. this._cache.orthoRight = undefined;
  22451. this._cache.orthoBottom = undefined;
  22452. this._cache.orthoTop = undefined;
  22453. this._cache.renderWidth = undefined;
  22454. this._cache.renderHeight = undefined;
  22455. };
  22456. Camera.prototype._updateCache = function (ignoreParentClass) {
  22457. if (!ignoreParentClass) {
  22458. _super.prototype._updateCache.call(this);
  22459. }
  22460. this._cache.position.copyFrom(this.position);
  22461. this._cache.upVector.copyFrom(this.upVector);
  22462. };
  22463. // Synchronized
  22464. Camera.prototype._isSynchronized = function () {
  22465. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22466. };
  22467. Camera.prototype._isSynchronizedViewMatrix = function () {
  22468. if (!_super.prototype._isSynchronized.call(this))
  22469. return false;
  22470. return this._cache.position.equals(this.position)
  22471. && this._cache.upVector.equals(this.upVector)
  22472. && this.isSynchronizedWithParent();
  22473. };
  22474. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22475. var check = this._cache.mode === this.mode
  22476. && this._cache.minZ === this.minZ
  22477. && this._cache.maxZ === this.maxZ;
  22478. if (!check) {
  22479. return false;
  22480. }
  22481. var engine = this.getEngine();
  22482. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22483. check = this._cache.fov === this.fov
  22484. && this._cache.fovMode === this.fovMode
  22485. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22486. }
  22487. else {
  22488. check = this._cache.orthoLeft === this.orthoLeft
  22489. && this._cache.orthoRight === this.orthoRight
  22490. && this._cache.orthoBottom === this.orthoBottom
  22491. && this._cache.orthoTop === this.orthoTop
  22492. && this._cache.renderWidth === engine.getRenderWidth()
  22493. && this._cache.renderHeight === engine.getRenderHeight();
  22494. }
  22495. return check;
  22496. };
  22497. // Controls
  22498. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22499. };
  22500. Camera.prototype.detachControl = function (element) {
  22501. };
  22502. Camera.prototype.update = function () {
  22503. this._checkInputs();
  22504. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22505. this._updateRigCameras();
  22506. }
  22507. };
  22508. Camera.prototype._checkInputs = function () {
  22509. this.onAfterCheckInputsObservable.notifyObservers(this);
  22510. };
  22511. Object.defineProperty(Camera.prototype, "rigCameras", {
  22512. get: function () {
  22513. return this._rigCameras;
  22514. },
  22515. enumerable: true,
  22516. configurable: true
  22517. });
  22518. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22519. get: function () {
  22520. return this._rigPostProcess;
  22521. },
  22522. enumerable: true,
  22523. configurable: true
  22524. });
  22525. /**
  22526. * Internal, gets the first post proces.
  22527. * @returns the first post process to be run on this camera.
  22528. */
  22529. Camera.prototype._getFirstPostProcess = function () {
  22530. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22531. if (this._postProcesses[ppIndex] !== null) {
  22532. return this._postProcesses[ppIndex];
  22533. }
  22534. }
  22535. return null;
  22536. };
  22537. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22538. // invalidate framebuffer
  22539. var firstPostProcess = this._getFirstPostProcess();
  22540. if (firstPostProcess) {
  22541. firstPostProcess.markTextureDirty();
  22542. }
  22543. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22544. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22545. var cam = this._rigCameras[i];
  22546. var rigPostProcess = cam._rigPostProcess;
  22547. // for VR rig, there does not have to be a post process
  22548. if (rigPostProcess) {
  22549. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22550. if (isPass) {
  22551. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22552. cam.isIntermediate = this._postProcesses.length === 0;
  22553. }
  22554. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22555. rigPostProcess.markTextureDirty();
  22556. }
  22557. else {
  22558. cam._postProcesses = this._postProcesses.slice(0);
  22559. }
  22560. }
  22561. };
  22562. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22563. if (insertAt === void 0) { insertAt = null; }
  22564. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22565. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22566. return 0;
  22567. }
  22568. if (insertAt == null || insertAt < 0) {
  22569. this._postProcesses.push(postProcess);
  22570. }
  22571. else if (this._postProcesses[insertAt] === null) {
  22572. this._postProcesses[insertAt] = postProcess;
  22573. }
  22574. else {
  22575. this._postProcesses.splice(insertAt, 0, postProcess);
  22576. }
  22577. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22578. return this._postProcesses.indexOf(postProcess);
  22579. };
  22580. Camera.prototype.detachPostProcess = function (postProcess) {
  22581. var idx = this._postProcesses.indexOf(postProcess);
  22582. if (idx !== -1) {
  22583. this._postProcesses[idx] = null;
  22584. }
  22585. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22586. };
  22587. Camera.prototype.getWorldMatrix = function () {
  22588. if (this._isSynchronizedViewMatrix()) {
  22589. return this._worldMatrix;
  22590. }
  22591. // Getting the the view matrix will also compute the world matrix.
  22592. this.getViewMatrix();
  22593. return this._worldMatrix;
  22594. };
  22595. Camera.prototype._getViewMatrix = function () {
  22596. return BABYLON.Matrix.Identity();
  22597. };
  22598. Camera.prototype.getViewMatrix = function (force) {
  22599. if (!force && this._isSynchronizedViewMatrix()) {
  22600. return this._computedViewMatrix;
  22601. }
  22602. this.updateCache();
  22603. this._computedViewMatrix = this._getViewMatrix();
  22604. this._currentRenderId = this.getScene().getRenderId();
  22605. this._childRenderId = this._currentRenderId;
  22606. this._refreshFrustumPlanes = true;
  22607. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22608. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22609. }
  22610. this.onViewMatrixChangedObservable.notifyObservers(this);
  22611. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22612. return this._computedViewMatrix;
  22613. };
  22614. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22615. this._doNotComputeProjectionMatrix = true;
  22616. if (projection !== undefined) {
  22617. this._projectionMatrix = projection;
  22618. }
  22619. };
  22620. ;
  22621. Camera.prototype.unfreezeProjectionMatrix = function () {
  22622. this._doNotComputeProjectionMatrix = false;
  22623. };
  22624. ;
  22625. Camera.prototype.getProjectionMatrix = function (force) {
  22626. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22627. return this._projectionMatrix;
  22628. }
  22629. // Cache
  22630. this._cache.mode = this.mode;
  22631. this._cache.minZ = this.minZ;
  22632. this._cache.maxZ = this.maxZ;
  22633. // Matrix
  22634. this._refreshFrustumPlanes = true;
  22635. var engine = this.getEngine();
  22636. var scene = this.getScene();
  22637. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22638. this._cache.fov = this.fov;
  22639. this._cache.fovMode = this.fovMode;
  22640. this._cache.aspectRatio = engine.getAspectRatio(this);
  22641. if (this.minZ <= 0) {
  22642. this.minZ = 0.1;
  22643. }
  22644. if (scene.useRightHandedSystem) {
  22645. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22646. }
  22647. else {
  22648. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22649. }
  22650. }
  22651. else {
  22652. var halfWidth = engine.getRenderWidth() / 2.0;
  22653. var halfHeight = engine.getRenderHeight() / 2.0;
  22654. if (scene.useRightHandedSystem) {
  22655. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22656. }
  22657. else {
  22658. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22659. }
  22660. this._cache.orthoLeft = this.orthoLeft;
  22661. this._cache.orthoRight = this.orthoRight;
  22662. this._cache.orthoBottom = this.orthoBottom;
  22663. this._cache.orthoTop = this.orthoTop;
  22664. this._cache.renderWidth = engine.getRenderWidth();
  22665. this._cache.renderHeight = engine.getRenderHeight();
  22666. }
  22667. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22668. return this._projectionMatrix;
  22669. };
  22670. Camera.prototype.getTranformationMatrix = function () {
  22671. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22672. return this._transformMatrix;
  22673. };
  22674. Camera.prototype.updateFrustumPlanes = function () {
  22675. if (!this._refreshFrustumPlanes) {
  22676. return;
  22677. }
  22678. this.getTranformationMatrix();
  22679. if (!this._frustumPlanes) {
  22680. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22681. }
  22682. else {
  22683. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22684. }
  22685. this._refreshFrustumPlanes = false;
  22686. };
  22687. Camera.prototype.isInFrustum = function (target) {
  22688. this.updateFrustumPlanes();
  22689. return target.isInFrustum(this._frustumPlanes);
  22690. };
  22691. Camera.prototype.isCompletelyInFrustum = function (target) {
  22692. this.updateFrustumPlanes();
  22693. return target.isCompletelyInFrustum(this._frustumPlanes);
  22694. };
  22695. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22696. if (length === void 0) { length = 100; }
  22697. if (!transform) {
  22698. transform = this.getWorldMatrix();
  22699. }
  22700. if (!origin) {
  22701. origin = this.position;
  22702. }
  22703. var forward = new BABYLON.Vector3(0, 0, 1);
  22704. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22705. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22706. return new BABYLON.Ray(origin, direction, length);
  22707. };
  22708. /**
  22709. * Releases resources associated with this node.
  22710. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22711. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22712. */
  22713. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22714. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22715. // Observables
  22716. this.onViewMatrixChangedObservable.clear();
  22717. this.onProjectionMatrixChangedObservable.clear();
  22718. this.onAfterCheckInputsObservable.clear();
  22719. this.onRestoreStateObservable.clear();
  22720. // Inputs
  22721. if (this.inputs) {
  22722. this.inputs.clear();
  22723. }
  22724. // Animations
  22725. this.getScene().stopAnimation(this);
  22726. // Remove from scene
  22727. this.getScene().removeCamera(this);
  22728. while (this._rigCameras.length > 0) {
  22729. var camera = this._rigCameras.pop();
  22730. if (camera) {
  22731. camera.dispose();
  22732. }
  22733. }
  22734. // Postprocesses
  22735. if (this._rigPostProcess) {
  22736. this._rigPostProcess.dispose(this);
  22737. this._rigPostProcess = null;
  22738. this._postProcesses = [];
  22739. }
  22740. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22741. this._rigPostProcess = null;
  22742. this._postProcesses = [];
  22743. }
  22744. else {
  22745. var i = this._postProcesses.length;
  22746. while (--i >= 0) {
  22747. var postProcess = this._postProcesses[i];
  22748. if (postProcess) {
  22749. postProcess.dispose(this);
  22750. }
  22751. }
  22752. }
  22753. // Render targets
  22754. var i = this.customRenderTargets.length;
  22755. while (--i >= 0) {
  22756. this.customRenderTargets[i].dispose();
  22757. }
  22758. this.customRenderTargets = [];
  22759. // Active Meshes
  22760. this._activeMeshes.dispose();
  22761. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22762. };
  22763. Object.defineProperty(Camera.prototype, "leftCamera", {
  22764. // ---- Camera rigs section ----
  22765. get: function () {
  22766. if (this._rigCameras.length < 1) {
  22767. return null;
  22768. }
  22769. return this._rigCameras[0];
  22770. },
  22771. enumerable: true,
  22772. configurable: true
  22773. });
  22774. Object.defineProperty(Camera.prototype, "rightCamera", {
  22775. get: function () {
  22776. if (this._rigCameras.length < 2) {
  22777. return null;
  22778. }
  22779. return this._rigCameras[1];
  22780. },
  22781. enumerable: true,
  22782. configurable: true
  22783. });
  22784. Camera.prototype.getLeftTarget = function () {
  22785. if (this._rigCameras.length < 1) {
  22786. return null;
  22787. }
  22788. return this._rigCameras[0].getTarget();
  22789. };
  22790. Camera.prototype.getRightTarget = function () {
  22791. if (this._rigCameras.length < 2) {
  22792. return null;
  22793. }
  22794. return this._rigCameras[1].getTarget();
  22795. };
  22796. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22797. if (this.cameraRigMode === mode) {
  22798. return;
  22799. }
  22800. while (this._rigCameras.length > 0) {
  22801. var camera = this._rigCameras.pop();
  22802. if (camera) {
  22803. camera.dispose();
  22804. }
  22805. }
  22806. this.cameraRigMode = mode;
  22807. this._cameraRigParams = {};
  22808. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22809. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22810. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22811. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22812. // create the rig cameras, unless none
  22813. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22814. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22815. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22816. if (leftCamera && rightCamera) {
  22817. this._rigCameras.push(leftCamera);
  22818. this._rigCameras.push(rightCamera);
  22819. }
  22820. }
  22821. switch (this.cameraRigMode) {
  22822. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22823. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22824. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22825. break;
  22826. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22827. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22828. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22829. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22830. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22831. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22832. break;
  22833. case Camera.RIG_MODE_VR:
  22834. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22835. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22836. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22837. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22838. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22839. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22840. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22841. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22842. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22843. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22844. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22845. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22846. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22847. if (metrics.compensateDistortion) {
  22848. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22849. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22850. }
  22851. break;
  22852. case Camera.RIG_MODE_WEBVR:
  22853. if (rigParams.vrDisplay) {
  22854. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22855. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22856. //Left eye
  22857. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22858. this._rigCameras[0].setCameraRigParameter("left", true);
  22859. //leaving this for future reference
  22860. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22861. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22862. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22863. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22864. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22865. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22866. this._rigCameras[0].parent = this;
  22867. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22868. //Right eye
  22869. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22870. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22871. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22872. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22873. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22874. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22875. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22876. this._rigCameras[1].parent = this;
  22877. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22878. if (Camera.UseAlternateWebVRRendering) {
  22879. this._rigCameras[1]._skipRendering = true;
  22880. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22881. }
  22882. }
  22883. break;
  22884. }
  22885. this._cascadePostProcessesToRigCams();
  22886. this.update();
  22887. };
  22888. Camera.prototype._getVRProjectionMatrix = function () {
  22889. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22890. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22891. return this._projectionMatrix;
  22892. };
  22893. Camera.prototype._updateCameraRotationMatrix = function () {
  22894. //Here for WebVR
  22895. };
  22896. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22897. //Here for WebVR
  22898. };
  22899. /**
  22900. * This function MUST be overwritten by the different WebVR cameras available.
  22901. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22902. */
  22903. Camera.prototype._getWebVRProjectionMatrix = function () {
  22904. return BABYLON.Matrix.Identity();
  22905. };
  22906. /**
  22907. * This function MUST be overwritten by the different WebVR cameras available.
  22908. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22909. */
  22910. Camera.prototype._getWebVRViewMatrix = function () {
  22911. return BABYLON.Matrix.Identity();
  22912. };
  22913. Camera.prototype.setCameraRigParameter = function (name, value) {
  22914. if (!this._cameraRigParams) {
  22915. this._cameraRigParams = {};
  22916. }
  22917. this._cameraRigParams[name] = value;
  22918. //provisionnally:
  22919. if (name === "interaxialDistance") {
  22920. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22921. }
  22922. };
  22923. /**
  22924. * needs to be overridden by children so sub has required properties to be copied
  22925. */
  22926. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22927. return null;
  22928. };
  22929. /**
  22930. * May need to be overridden by children
  22931. */
  22932. Camera.prototype._updateRigCameras = function () {
  22933. for (var i = 0; i < this._rigCameras.length; i++) {
  22934. this._rigCameras[i].minZ = this.minZ;
  22935. this._rigCameras[i].maxZ = this.maxZ;
  22936. this._rigCameras[i].fov = this.fov;
  22937. }
  22938. // only update viewport when ANAGLYPH
  22939. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22940. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22941. }
  22942. };
  22943. Camera.prototype._setupInputs = function () {
  22944. };
  22945. Camera.prototype.serialize = function () {
  22946. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22947. // Type
  22948. serializationObject.type = this.getClassName();
  22949. // Parent
  22950. if (this.parent) {
  22951. serializationObject.parentId = this.parent.id;
  22952. }
  22953. if (this.inputs) {
  22954. this.inputs.serialize(serializationObject);
  22955. }
  22956. // Animations
  22957. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22958. serializationObject.ranges = this.serializeAnimationRanges();
  22959. return serializationObject;
  22960. };
  22961. Camera.prototype.clone = function (name) {
  22962. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22963. };
  22964. Camera.prototype.getDirection = function (localAxis) {
  22965. var result = BABYLON.Vector3.Zero();
  22966. this.getDirectionToRef(localAxis, result);
  22967. return result;
  22968. };
  22969. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22970. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22971. };
  22972. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22973. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22974. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22975. switch (type) {
  22976. case "ArcRotateCamera":
  22977. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22978. case "DeviceOrientationCamera":
  22979. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22980. case "FollowCamera":
  22981. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22982. case "ArcFollowCamera":
  22983. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22984. case "GamepadCamera":
  22985. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22986. case "TouchCamera":
  22987. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22988. case "VirtualJoysticksCamera":
  22989. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22990. case "WebVRFreeCamera":
  22991. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22992. case "WebVRGamepadCamera":
  22993. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22994. case "VRDeviceOrientationFreeCamera":
  22995. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22996. case "VRDeviceOrientationGamepadCamera":
  22997. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22998. case "AnaglyphArcRotateCamera":
  22999. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23000. case "AnaglyphFreeCamera":
  23001. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23002. case "AnaglyphGamepadCamera":
  23003. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23004. case "AnaglyphUniversalCamera":
  23005. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23006. case "StereoscopicArcRotateCamera":
  23007. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23008. case "StereoscopicFreeCamera":
  23009. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23010. case "StereoscopicGamepadCamera":
  23011. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23012. case "StereoscopicUniversalCamera":
  23013. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23014. case "FreeCamera": // Forcing Universal here
  23015. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23016. default: // Universal Camera is the default value
  23017. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23018. }
  23019. };
  23020. Camera.prototype.computeWorldMatrix = function () {
  23021. return this.getWorldMatrix();
  23022. };
  23023. Camera.Parse = function (parsedCamera, scene) {
  23024. var type = parsedCamera.type;
  23025. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23026. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23027. // Parent
  23028. if (parsedCamera.parentId) {
  23029. camera._waitingParentId = parsedCamera.parentId;
  23030. }
  23031. //If camera has an input manager, let it parse inputs settings
  23032. if (camera.inputs) {
  23033. camera.inputs.parse(parsedCamera);
  23034. camera._setupInputs();
  23035. }
  23036. if (camera.setPosition) { // need to force position
  23037. camera.position.copyFromFloats(0, 0, 0);
  23038. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23039. }
  23040. // Target
  23041. if (parsedCamera.target) {
  23042. if (camera.setTarget) {
  23043. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23044. }
  23045. }
  23046. // Apply 3d rig, when found
  23047. if (parsedCamera.cameraRigMode) {
  23048. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23049. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23050. }
  23051. // Animations
  23052. if (parsedCamera.animations) {
  23053. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23054. var parsedAnimation = parsedCamera.animations[animationIndex];
  23055. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23056. }
  23057. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23058. }
  23059. if (parsedCamera.autoAnimate) {
  23060. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23061. }
  23062. return camera;
  23063. };
  23064. // Statics
  23065. Camera._PERSPECTIVE_CAMERA = 0;
  23066. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23067. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23068. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23069. Camera._RIG_MODE_NONE = 0;
  23070. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23071. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23072. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23073. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23074. Camera._RIG_MODE_VR = 20;
  23075. Camera._RIG_MODE_WEBVR = 21;
  23076. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23077. Camera.UseAlternateWebVRRendering = false;
  23078. __decorate([
  23079. BABYLON.serializeAsVector3()
  23080. ], Camera.prototype, "position", void 0);
  23081. __decorate([
  23082. BABYLON.serializeAsVector3()
  23083. ], Camera.prototype, "upVector", void 0);
  23084. __decorate([
  23085. BABYLON.serialize()
  23086. ], Camera.prototype, "orthoLeft", void 0);
  23087. __decorate([
  23088. BABYLON.serialize()
  23089. ], Camera.prototype, "orthoRight", void 0);
  23090. __decorate([
  23091. BABYLON.serialize()
  23092. ], Camera.prototype, "orthoBottom", void 0);
  23093. __decorate([
  23094. BABYLON.serialize()
  23095. ], Camera.prototype, "orthoTop", void 0);
  23096. __decorate([
  23097. BABYLON.serialize()
  23098. ], Camera.prototype, "fov", void 0);
  23099. __decorate([
  23100. BABYLON.serialize()
  23101. ], Camera.prototype, "minZ", void 0);
  23102. __decorate([
  23103. BABYLON.serialize()
  23104. ], Camera.prototype, "maxZ", void 0);
  23105. __decorate([
  23106. BABYLON.serialize()
  23107. ], Camera.prototype, "inertia", void 0);
  23108. __decorate([
  23109. BABYLON.serialize()
  23110. ], Camera.prototype, "mode", void 0);
  23111. __decorate([
  23112. BABYLON.serialize()
  23113. ], Camera.prototype, "layerMask", void 0);
  23114. __decorate([
  23115. BABYLON.serialize()
  23116. ], Camera.prototype, "fovMode", void 0);
  23117. __decorate([
  23118. BABYLON.serialize()
  23119. ], Camera.prototype, "cameraRigMode", void 0);
  23120. __decorate([
  23121. BABYLON.serialize()
  23122. ], Camera.prototype, "interaxialDistance", void 0);
  23123. __decorate([
  23124. BABYLON.serialize()
  23125. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23126. return Camera;
  23127. }(BABYLON.Node));
  23128. BABYLON.Camera = Camera;
  23129. })(BABYLON || (BABYLON = {}));
  23130. //# sourceMappingURL=babylon.camera.js.map
  23131. var BABYLON;
  23132. (function (BABYLON) {
  23133. var RenderingManager = /** @class */ (function () {
  23134. function RenderingManager(scene) {
  23135. this._renderingGroups = new Array();
  23136. this._autoClearDepthStencil = {};
  23137. this._customOpaqueSortCompareFn = {};
  23138. this._customAlphaTestSortCompareFn = {};
  23139. this._customTransparentSortCompareFn = {};
  23140. this._renderinGroupInfo = null;
  23141. this._scene = scene;
  23142. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23143. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23144. }
  23145. }
  23146. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23147. if (depth === void 0) { depth = true; }
  23148. if (stencil === void 0) { stencil = true; }
  23149. if (this._depthStencilBufferAlreadyCleaned) {
  23150. return;
  23151. }
  23152. this._scene.getEngine().clear(null, false, depth, stencil);
  23153. this._depthStencilBufferAlreadyCleaned = true;
  23154. };
  23155. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23156. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23157. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23158. var info = null;
  23159. if (observable) {
  23160. if (!this._renderinGroupInfo) {
  23161. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23162. }
  23163. info = this._renderinGroupInfo;
  23164. info.scene = this._scene;
  23165. info.camera = this._scene.activeCamera;
  23166. }
  23167. // Dispatch sprites
  23168. if (renderSprites) {
  23169. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23170. var manager = this._scene.spriteManagers[index];
  23171. this.dispatchSprites(manager);
  23172. }
  23173. }
  23174. // Render
  23175. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23176. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23177. var renderingGroup = this._renderingGroups[index];
  23178. if (!renderingGroup && !observable)
  23179. continue;
  23180. var renderingGroupMask = 0;
  23181. // Fire PRECLEAR stage
  23182. if (observable && info) {
  23183. renderingGroupMask = Math.pow(2, index);
  23184. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23185. info.renderingGroupId = index;
  23186. observable.notifyObservers(info, renderingGroupMask);
  23187. }
  23188. // Clear depth/stencil if needed
  23189. if (RenderingManager.AUTOCLEAR) {
  23190. var autoClear = this._autoClearDepthStencil[index];
  23191. if (autoClear && autoClear.autoClear) {
  23192. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23193. }
  23194. }
  23195. if (observable && info) {
  23196. // Fire PREOPAQUE stage
  23197. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23198. observable.notifyObservers(info, renderingGroupMask);
  23199. // Fire PRETRANSPARENT stage
  23200. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23201. observable.notifyObservers(info, renderingGroupMask);
  23202. }
  23203. if (renderingGroup)
  23204. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23205. // Fire POSTTRANSPARENT stage
  23206. if (observable && info) {
  23207. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23208. observable.notifyObservers(info, renderingGroupMask);
  23209. }
  23210. }
  23211. };
  23212. RenderingManager.prototype.reset = function () {
  23213. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23214. var renderingGroup = this._renderingGroups[index];
  23215. if (renderingGroup) {
  23216. renderingGroup.prepare();
  23217. }
  23218. }
  23219. };
  23220. RenderingManager.prototype.dispose = function () {
  23221. this.freeRenderingGroups();
  23222. this._renderingGroups.length = 0;
  23223. };
  23224. /**
  23225. * Clear the info related to rendering groups preventing retention points during dispose.
  23226. */
  23227. RenderingManager.prototype.freeRenderingGroups = function () {
  23228. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23229. var renderingGroup = this._renderingGroups[index];
  23230. if (renderingGroup) {
  23231. renderingGroup.dispose();
  23232. }
  23233. }
  23234. };
  23235. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23236. if (this._renderingGroups[renderingGroupId] === undefined) {
  23237. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23238. }
  23239. };
  23240. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23241. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23242. this._prepareRenderingGroup(renderingGroupId);
  23243. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23244. };
  23245. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23246. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23247. this._prepareRenderingGroup(renderingGroupId);
  23248. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23249. };
  23250. /**
  23251. * @param subMesh The submesh to dispatch
  23252. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23253. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23254. */
  23255. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23256. if (mesh === undefined) {
  23257. mesh = subMesh.getMesh();
  23258. }
  23259. var renderingGroupId = mesh.renderingGroupId || 0;
  23260. this._prepareRenderingGroup(renderingGroupId);
  23261. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23262. };
  23263. /**
  23264. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23265. * This allowed control for front to back rendering or reversly depending of the special needs.
  23266. *
  23267. * @param renderingGroupId The rendering group id corresponding to its index
  23268. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23269. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23270. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23271. */
  23272. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23273. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23274. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23275. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23276. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23277. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23278. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23279. if (this._renderingGroups[renderingGroupId]) {
  23280. var group = this._renderingGroups[renderingGroupId];
  23281. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23282. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23283. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23284. }
  23285. };
  23286. /**
  23287. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23288. *
  23289. * @param renderingGroupId The rendering group id corresponding to its index
  23290. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23291. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23292. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23293. */
  23294. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23295. if (depth === void 0) { depth = true; }
  23296. if (stencil === void 0) { stencil = true; }
  23297. this._autoClearDepthStencil[renderingGroupId] = {
  23298. autoClear: autoClearDepthStencil,
  23299. depth: depth,
  23300. stencil: stencil
  23301. };
  23302. };
  23303. /**
  23304. * The max id used for rendering groups (not included)
  23305. */
  23306. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23307. /**
  23308. * The min id used for rendering groups (included)
  23309. */
  23310. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23311. /**
  23312. * Used to globally prevent autoclearing scenes.
  23313. */
  23314. RenderingManager.AUTOCLEAR = true;
  23315. return RenderingManager;
  23316. }());
  23317. BABYLON.RenderingManager = RenderingManager;
  23318. })(BABYLON || (BABYLON = {}));
  23319. //# sourceMappingURL=babylon.renderingManager.js.map
  23320. var BABYLON;
  23321. (function (BABYLON) {
  23322. var RenderingGroup = /** @class */ (function () {
  23323. /**
  23324. * Creates a new rendering group.
  23325. * @param index The rendering group index
  23326. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23327. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23328. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23329. */
  23330. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23331. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23332. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23333. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23334. this.index = index;
  23335. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23336. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23337. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23338. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23339. this._particleSystems = new BABYLON.SmartArray(256);
  23340. this._spriteManagers = new BABYLON.SmartArray(256);
  23341. this._edgesRenderers = new BABYLON.SmartArray(16);
  23342. this._scene = scene;
  23343. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23344. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23345. this.transparentSortCompareFn = transparentSortCompareFn;
  23346. }
  23347. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23348. /**
  23349. * Set the opaque sort comparison function.
  23350. * If null the sub meshes will be render in the order they were created
  23351. */
  23352. set: function (value) {
  23353. this._opaqueSortCompareFn = value;
  23354. if (value) {
  23355. this._renderOpaque = this.renderOpaqueSorted;
  23356. }
  23357. else {
  23358. this._renderOpaque = RenderingGroup.renderUnsorted;
  23359. }
  23360. },
  23361. enumerable: true,
  23362. configurable: true
  23363. });
  23364. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23365. /**
  23366. * Set the alpha test sort comparison function.
  23367. * If null the sub meshes will be render in the order they were created
  23368. */
  23369. set: function (value) {
  23370. this._alphaTestSortCompareFn = value;
  23371. if (value) {
  23372. this._renderAlphaTest = this.renderAlphaTestSorted;
  23373. }
  23374. else {
  23375. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23376. }
  23377. },
  23378. enumerable: true,
  23379. configurable: true
  23380. });
  23381. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23382. /**
  23383. * Set the transparent sort comparison function.
  23384. * If null the sub meshes will be render in the order they were created
  23385. */
  23386. set: function (value) {
  23387. if (value) {
  23388. this._transparentSortCompareFn = value;
  23389. }
  23390. else {
  23391. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23392. }
  23393. this._renderTransparent = this.renderTransparentSorted;
  23394. },
  23395. enumerable: true,
  23396. configurable: true
  23397. });
  23398. /**
  23399. * Render all the sub meshes contained in the group.
  23400. * @param customRenderFunction Used to override the default render behaviour of the group.
  23401. * @returns true if rendered some submeshes.
  23402. */
  23403. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23404. if (customRenderFunction) {
  23405. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23406. return;
  23407. }
  23408. var engine = this._scene.getEngine();
  23409. // Depth only
  23410. if (this._depthOnlySubMeshes.length !== 0) {
  23411. engine.setColorWrite(false);
  23412. this._renderAlphaTest(this._depthOnlySubMeshes);
  23413. engine.setColorWrite(true);
  23414. }
  23415. // Opaque
  23416. if (this._opaqueSubMeshes.length !== 0) {
  23417. this._renderOpaque(this._opaqueSubMeshes);
  23418. }
  23419. // Alpha test
  23420. if (this._alphaTestSubMeshes.length !== 0) {
  23421. this._renderAlphaTest(this._alphaTestSubMeshes);
  23422. }
  23423. var stencilState = engine.getStencilBuffer();
  23424. engine.setStencilBuffer(false);
  23425. // Sprites
  23426. if (renderSprites) {
  23427. this._renderSprites();
  23428. }
  23429. // Particles
  23430. if (renderParticles) {
  23431. this._renderParticles(activeMeshes);
  23432. }
  23433. if (this.onBeforeTransparentRendering) {
  23434. this.onBeforeTransparentRendering();
  23435. }
  23436. // Transparent
  23437. if (this._transparentSubMeshes.length !== 0) {
  23438. this._renderTransparent(this._transparentSubMeshes);
  23439. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23440. }
  23441. // Set back stencil to false in case it changes before the edge renderer.
  23442. engine.setStencilBuffer(false);
  23443. // Edges
  23444. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23445. this._edgesRenderers.data[edgesRendererIndex].render();
  23446. }
  23447. // Restore Stencil state.
  23448. engine.setStencilBuffer(stencilState);
  23449. };
  23450. /**
  23451. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23452. * @param subMeshes The submeshes to render
  23453. */
  23454. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23455. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23456. };
  23457. /**
  23458. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23459. * @param subMeshes The submeshes to render
  23460. */
  23461. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23462. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23463. };
  23464. /**
  23465. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23466. * @param subMeshes The submeshes to render
  23467. */
  23468. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23469. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23470. };
  23471. /**
  23472. * Renders the submeshes in a specified order.
  23473. * @param subMeshes The submeshes to sort before render
  23474. * @param sortCompareFn The comparison function use to sort
  23475. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23476. * @param transparent Specifies to activate blending if true
  23477. */
  23478. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23479. var subIndex = 0;
  23480. var subMesh;
  23481. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23482. for (; subIndex < subMeshes.length; subIndex++) {
  23483. subMesh = subMeshes.data[subIndex];
  23484. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23485. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23486. }
  23487. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23488. if (sortCompareFn) {
  23489. sortedArray.sort(sortCompareFn);
  23490. }
  23491. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23492. subMesh = sortedArray[subIndex];
  23493. if (transparent) {
  23494. var material = subMesh.getMaterial();
  23495. if (material && material.needDepthPrePass) {
  23496. var engine = material.getScene().getEngine();
  23497. engine.setColorWrite(false);
  23498. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23499. subMesh.render(false);
  23500. engine.setColorWrite(true);
  23501. }
  23502. }
  23503. subMesh.render(transparent);
  23504. }
  23505. };
  23506. /**
  23507. * Renders the submeshes in the order they were dispatched (no sort applied).
  23508. * @param subMeshes The submeshes to render
  23509. */
  23510. RenderingGroup.renderUnsorted = function (subMeshes) {
  23511. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23512. var submesh = subMeshes.data[subIndex];
  23513. submesh.render(false);
  23514. }
  23515. };
  23516. /**
  23517. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23518. * are rendered back to front if in the same alpha index.
  23519. *
  23520. * @param a The first submesh
  23521. * @param b The second submesh
  23522. * @returns The result of the comparison
  23523. */
  23524. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23525. // Alpha index first
  23526. if (a._alphaIndex > b._alphaIndex) {
  23527. return 1;
  23528. }
  23529. if (a._alphaIndex < b._alphaIndex) {
  23530. return -1;
  23531. }
  23532. // Then distance to camera
  23533. return RenderingGroup.backToFrontSortCompare(a, b);
  23534. };
  23535. /**
  23536. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23537. * are rendered back to front.
  23538. *
  23539. * @param a The first submesh
  23540. * @param b The second submesh
  23541. * @returns The result of the comparison
  23542. */
  23543. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23544. // Then distance to camera
  23545. if (a._distanceToCamera < b._distanceToCamera) {
  23546. return 1;
  23547. }
  23548. if (a._distanceToCamera > b._distanceToCamera) {
  23549. return -1;
  23550. }
  23551. return 0;
  23552. };
  23553. /**
  23554. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23555. * are rendered front to back (prevent overdraw).
  23556. *
  23557. * @param a The first submesh
  23558. * @param b The second submesh
  23559. * @returns The result of the comparison
  23560. */
  23561. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23562. // Then distance to camera
  23563. if (a._distanceToCamera < b._distanceToCamera) {
  23564. return -1;
  23565. }
  23566. if (a._distanceToCamera > b._distanceToCamera) {
  23567. return 1;
  23568. }
  23569. return 0;
  23570. };
  23571. /**
  23572. * Resets the different lists of submeshes to prepare a new frame.
  23573. */
  23574. RenderingGroup.prototype.prepare = function () {
  23575. this._opaqueSubMeshes.reset();
  23576. this._transparentSubMeshes.reset();
  23577. this._alphaTestSubMeshes.reset();
  23578. this._depthOnlySubMeshes.reset();
  23579. this._particleSystems.reset();
  23580. this._spriteManagers.reset();
  23581. this._edgesRenderers.reset();
  23582. };
  23583. RenderingGroup.prototype.dispose = function () {
  23584. this._opaqueSubMeshes.dispose();
  23585. this._transparentSubMeshes.dispose();
  23586. this._alphaTestSubMeshes.dispose();
  23587. this._depthOnlySubMeshes.dispose();
  23588. this._particleSystems.dispose();
  23589. this._spriteManagers.dispose();
  23590. this._edgesRenderers.dispose();
  23591. };
  23592. /**
  23593. * Inserts the submesh in its correct queue depending on its material.
  23594. * @param subMesh The submesh to dispatch
  23595. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23596. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23597. */
  23598. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23599. // Get mesh and materials if not provided
  23600. if (mesh === undefined) {
  23601. mesh = subMesh.getMesh();
  23602. }
  23603. if (material === undefined) {
  23604. material = subMesh.getMaterial();
  23605. }
  23606. if (material === null || material === undefined) {
  23607. return;
  23608. }
  23609. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23610. this._transparentSubMeshes.push(subMesh);
  23611. }
  23612. else if (material.needAlphaTesting()) { // Alpha test
  23613. if (material.needDepthPrePass) {
  23614. this._depthOnlySubMeshes.push(subMesh);
  23615. }
  23616. this._alphaTestSubMeshes.push(subMesh);
  23617. }
  23618. else {
  23619. if (material.needDepthPrePass) {
  23620. this._depthOnlySubMeshes.push(subMesh);
  23621. }
  23622. this._opaqueSubMeshes.push(subMesh); // Opaque
  23623. }
  23624. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23625. this._edgesRenderers.push(mesh._edgesRenderer);
  23626. }
  23627. };
  23628. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23629. this._spriteManagers.push(spriteManager);
  23630. };
  23631. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23632. this._particleSystems.push(particleSystem);
  23633. };
  23634. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23635. if (this._particleSystems.length === 0) {
  23636. return;
  23637. }
  23638. // Particles
  23639. var activeCamera = this._scene.activeCamera;
  23640. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23641. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23642. var particleSystem = this._particleSystems.data[particleIndex];
  23643. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23644. continue;
  23645. }
  23646. var emitter = particleSystem.emitter;
  23647. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23648. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23649. }
  23650. }
  23651. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23652. };
  23653. RenderingGroup.prototype._renderSprites = function () {
  23654. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23655. return;
  23656. }
  23657. // Sprites
  23658. var activeCamera = this._scene.activeCamera;
  23659. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23660. for (var id = 0; id < this._spriteManagers.length; id++) {
  23661. var spriteManager = this._spriteManagers.data[id];
  23662. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23663. spriteManager.render();
  23664. }
  23665. }
  23666. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23667. };
  23668. return RenderingGroup;
  23669. }());
  23670. BABYLON.RenderingGroup = RenderingGroup;
  23671. })(BABYLON || (BABYLON = {}));
  23672. //# sourceMappingURL=babylon.renderingGroup.js.map
  23673. var BABYLON;
  23674. (function (BABYLON) {
  23675. /** @hidden */
  23676. var ClickInfo = /** @class */ (function () {
  23677. function ClickInfo() {
  23678. this._singleClick = false;
  23679. this._doubleClick = false;
  23680. this._hasSwiped = false;
  23681. this._ignore = false;
  23682. }
  23683. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23684. get: function () {
  23685. return this._singleClick;
  23686. },
  23687. set: function (b) {
  23688. this._singleClick = b;
  23689. },
  23690. enumerable: true,
  23691. configurable: true
  23692. });
  23693. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23694. get: function () {
  23695. return this._doubleClick;
  23696. },
  23697. set: function (b) {
  23698. this._doubleClick = b;
  23699. },
  23700. enumerable: true,
  23701. configurable: true
  23702. });
  23703. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23704. get: function () {
  23705. return this._hasSwiped;
  23706. },
  23707. set: function (b) {
  23708. this._hasSwiped = b;
  23709. },
  23710. enumerable: true,
  23711. configurable: true
  23712. });
  23713. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23714. get: function () {
  23715. return this._ignore;
  23716. },
  23717. set: function (b) {
  23718. this._ignore = b;
  23719. },
  23720. enumerable: true,
  23721. configurable: true
  23722. });
  23723. return ClickInfo;
  23724. }());
  23725. /**
  23726. * This class is used by the onRenderingGroupObservable
  23727. */
  23728. var RenderingGroupInfo = /** @class */ (function () {
  23729. function RenderingGroupInfo() {
  23730. }
  23731. /**
  23732. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23733. * This stage will be fired no matter what
  23734. */
  23735. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23736. /**
  23737. * Called before opaque object are rendered.
  23738. * This stage will be fired only if there's 3D Opaque content to render
  23739. */
  23740. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23741. /**
  23742. * Called after the opaque objects are rendered and before the transparent ones
  23743. * This stage will be fired only if there's 3D transparent content to render
  23744. */
  23745. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23746. /**
  23747. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23748. * This stage will be fired no matter what
  23749. */
  23750. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23751. return RenderingGroupInfo;
  23752. }());
  23753. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23754. /**
  23755. * Represents a scene to be rendered by the engine.
  23756. * @see http://doc.babylonjs.com/features/scene
  23757. */
  23758. var Scene = /** @class */ (function () {
  23759. /**
  23760. * Creates a new Scene
  23761. * @param engine defines the engine to use to render this scene
  23762. */
  23763. function Scene(engine) {
  23764. // Members
  23765. /**
  23766. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23767. */
  23768. this.autoClear = true;
  23769. /**
  23770. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23771. */
  23772. this.autoClearDepthAndStencil = true;
  23773. /**
  23774. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23775. */
  23776. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23777. /**
  23778. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23779. */
  23780. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23781. this._forceWireframe = false;
  23782. this._forcePointsCloud = false;
  23783. /**
  23784. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23785. */
  23786. this.forceShowBoundingBoxes = false;
  23787. /**
  23788. * Gets or sets a boolean indicating if animations are enabled
  23789. */
  23790. this.animationsEnabled = true;
  23791. this._animationPropertiesOverride = null;
  23792. /**
  23793. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23794. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23795. */
  23796. this.useConstantAnimationDeltaTime = false;
  23797. /**
  23798. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23799. * Please note that it requires to run a ray cast through the scene on every frame
  23800. */
  23801. this.constantlyUpdateMeshUnderPointer = false;
  23802. /**
  23803. * Defines the HTML cursor to use when hovering over interactive elements
  23804. */
  23805. this.hoverCursor = "pointer";
  23806. /**
  23807. * Defines the HTML default cursor to use (empty by default)
  23808. */
  23809. this.defaultCursor = "";
  23810. /**
  23811. * This is used to call preventDefault() on pointer down
  23812. * in order to block unwanted artifacts like system double clicks
  23813. */
  23814. this.preventDefaultOnPointerDown = true;
  23815. // Metadata
  23816. /**
  23817. * Gets or sets user defined metadata
  23818. */
  23819. this.metadata = null;
  23820. /**
  23821. * Use this array to add regular expressions used to disable offline support for specific urls
  23822. */
  23823. this.disableOfflineSupportExceptionRules = new Array();
  23824. /**
  23825. * An event triggered when the scene is disposed.
  23826. */
  23827. this.onDisposeObservable = new BABYLON.Observable();
  23828. this._onDisposeObserver = null;
  23829. /**
  23830. * An event triggered before rendering the scene (right after animations and physics)
  23831. */
  23832. this.onBeforeRenderObservable = new BABYLON.Observable();
  23833. this._onBeforeRenderObserver = null;
  23834. /**
  23835. * An event triggered after rendering the scene
  23836. */
  23837. this.onAfterRenderObservable = new BABYLON.Observable();
  23838. this._onAfterRenderObserver = null;
  23839. /**
  23840. * An event triggered before animating the scene
  23841. */
  23842. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23843. /**
  23844. * An event triggered after animations processing
  23845. */
  23846. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23847. /**
  23848. * An event triggered before draw calls are ready to be sent
  23849. */
  23850. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23851. /**
  23852. * An event triggered after draw calls have been sent
  23853. */
  23854. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23855. /**
  23856. * An event triggered when physic simulation is about to be run
  23857. */
  23858. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23859. /**
  23860. * An event triggered when physic simulation has been done
  23861. */
  23862. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23863. /**
  23864. * An event triggered when the scene is ready
  23865. */
  23866. this.onReadyObservable = new BABYLON.Observable();
  23867. /**
  23868. * An event triggered before rendering a camera
  23869. */
  23870. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23871. this._onBeforeCameraRenderObserver = null;
  23872. /**
  23873. * An event triggered after rendering a camera
  23874. */
  23875. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23876. this._onAfterCameraRenderObserver = null;
  23877. /**
  23878. * An event triggered when active meshes evaluation is about to start
  23879. */
  23880. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23881. /**
  23882. * An event triggered when active meshes evaluation is done
  23883. */
  23884. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23885. /**
  23886. * An event triggered when particles rendering is about to start
  23887. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23888. */
  23889. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23890. /**
  23891. * An event triggered when particles rendering is done
  23892. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23893. */
  23894. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23895. /**
  23896. * An event triggered when sprites rendering is about to start
  23897. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23898. */
  23899. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23900. /**
  23901. * An event triggered when sprites rendering is done
  23902. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23903. */
  23904. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23905. /**
  23906. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23907. */
  23908. this.onDataLoadedObservable = new BABYLON.Observable();
  23909. /**
  23910. * An event triggered when a camera is created
  23911. */
  23912. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23913. /**
  23914. * An event triggered when a camera is removed
  23915. */
  23916. this.onCameraRemovedObservable = new BABYLON.Observable();
  23917. /**
  23918. * An event triggered when a light is created
  23919. */
  23920. this.onNewLightAddedObservable = new BABYLON.Observable();
  23921. /**
  23922. * An event triggered when a light is removed
  23923. */
  23924. this.onLightRemovedObservable = new BABYLON.Observable();
  23925. /**
  23926. * An event triggered when a geometry is created
  23927. */
  23928. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23929. /**
  23930. * An event triggered when a geometry is removed
  23931. */
  23932. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23933. /**
  23934. * An event triggered when a transform node is created
  23935. */
  23936. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23937. /**
  23938. * An event triggered when a transform node is removed
  23939. */
  23940. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23941. /**
  23942. * An event triggered when a mesh is created
  23943. */
  23944. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23945. /**
  23946. * An event triggered when a mesh is removed
  23947. */
  23948. this.onMeshRemovedObservable = new BABYLON.Observable();
  23949. /**
  23950. * An event triggered when render targets are about to be rendered
  23951. * Can happen multiple times per frame.
  23952. */
  23953. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23954. /**
  23955. * An event triggered when render targets were rendered.
  23956. * Can happen multiple times per frame.
  23957. */
  23958. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23959. /**
  23960. * An event triggered before calculating deterministic simulation step
  23961. */
  23962. this.onBeforeStepObservable = new BABYLON.Observable();
  23963. /**
  23964. * An event triggered after calculating deterministic simulation step
  23965. */
  23966. this.onAfterStepObservable = new BABYLON.Observable();
  23967. /**
  23968. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23969. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23970. * 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)
  23971. */
  23972. this.onRenderingGroupObservable = new BABYLON.Observable();
  23973. // Animations
  23974. /**
  23975. * Gets a list of Animations associated with the scene
  23976. */
  23977. this.animations = [];
  23978. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23979. /**
  23980. * 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).
  23981. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23982. */
  23983. this.onPrePointerObservable = new BABYLON.Observable();
  23984. /**
  23985. * Observable event triggered each time an input event is received from the rendering canvas
  23986. */
  23987. this.onPointerObservable = new BABYLON.Observable();
  23988. this._meshPickProceed = false;
  23989. this._currentPickResult = null;
  23990. this._previousPickResult = null;
  23991. this._totalPointersPressed = 0;
  23992. this._doubleClickOccured = false;
  23993. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23994. this.cameraToUseForPointers = null;
  23995. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23996. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23997. this._startingPointerTime = 0;
  23998. this._previousStartingPointerTime = 0;
  23999. this._pointerCaptures = {};
  24000. // Deterministic lockstep
  24001. this._timeAccumulator = 0;
  24002. this._currentStepId = 0;
  24003. this._currentInternalStep = 0;
  24004. // Keyboard
  24005. /**
  24006. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24007. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24008. */
  24009. this.onPreKeyboardObservable = new BABYLON.Observable();
  24010. /**
  24011. * Observable event triggered each time an keyboard event is received from the hosting window
  24012. */
  24013. this.onKeyboardObservable = new BABYLON.Observable();
  24014. // Coordinates system
  24015. this._useRightHandedSystem = false;
  24016. // Fog
  24017. this._fogEnabled = true;
  24018. this._fogMode = Scene.FOGMODE_NONE;
  24019. /**
  24020. * Gets or sets the fog color to use
  24021. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24022. */
  24023. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24024. /**
  24025. * Gets or sets the fog density to use
  24026. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24027. */
  24028. this.fogDensity = 0.1;
  24029. /**
  24030. * Gets or sets the fog start distance to use
  24031. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24032. */
  24033. this.fogStart = 0;
  24034. /**
  24035. * Gets or sets the fog end distance to use
  24036. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24037. */
  24038. this.fogEnd = 1000.0;
  24039. // Lights
  24040. this._shadowsEnabled = true;
  24041. this._lightsEnabled = true;
  24042. /**
  24043. * All of the lights added to this scene
  24044. * @see http://doc.babylonjs.com/babylon101/lights
  24045. */
  24046. this.lights = new Array();
  24047. // Cameras
  24048. /** All of the cameras added to this scene.
  24049. * @see http://doc.babylonjs.com/babylon101/cameras
  24050. */
  24051. this.cameras = new Array();
  24052. /** All of the active cameras added to this scene. */
  24053. this.activeCameras = new Array();
  24054. // Meshes
  24055. /**
  24056. * All of the tranform nodes added to this scene
  24057. * @see http://doc.babylonjs.com/how_to/transformnode
  24058. */
  24059. this.transformNodes = new Array();
  24060. /**
  24061. * All of the (abstract) meshes added to this scene
  24062. */
  24063. this.meshes = new Array();
  24064. /**
  24065. * All of the animation groups added to this scene
  24066. * @see http://doc.babylonjs.com/how_to/group
  24067. */
  24068. this.animationGroups = new Array();
  24069. // Geometries
  24070. this._geometries = new Array();
  24071. /**
  24072. * All of the materials added to this scene
  24073. * @see http://doc.babylonjs.com/babylon101/materials
  24074. */
  24075. this.materials = new Array();
  24076. /**
  24077. * All of the multi-materials added to this scene
  24078. * @see http://doc.babylonjs.com/how_to/multi_materials
  24079. */
  24080. this.multiMaterials = new Array();
  24081. // Textures
  24082. this._texturesEnabled = true;
  24083. /**
  24084. * All of the textures added to this scene
  24085. */
  24086. this.textures = new Array();
  24087. // Particles
  24088. /**
  24089. * Gets or sets a boolean indicating if particles are enabled on this scene
  24090. */
  24091. this.particlesEnabled = true;
  24092. /**
  24093. * All of the particle systems added to this scene
  24094. * @see http://doc.babylonjs.com/babylon101/particles
  24095. */
  24096. this.particleSystems = new Array();
  24097. // Sprites
  24098. /**
  24099. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24100. */
  24101. this.spritesEnabled = true;
  24102. /**
  24103. * All of the sprite managers added to this scene
  24104. * @see http://doc.babylonjs.com/babylon101/sprites
  24105. */
  24106. this.spriteManagers = new Array();
  24107. /**
  24108. * The list of layers (background and foreground) of the scene
  24109. */
  24110. this.layers = new Array();
  24111. /**
  24112. * The list of effect layers (highlights/glow) added to the scene
  24113. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24114. * @see http://doc.babylonjs.com/how_to/glow_layer
  24115. */
  24116. this.effectLayers = new Array();
  24117. // Skeletons
  24118. this._skeletonsEnabled = true;
  24119. /**
  24120. * The list of skeletons added to the scene
  24121. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24122. */
  24123. this.skeletons = new Array();
  24124. // Morph targets
  24125. /**
  24126. * The list of morph target managers added to the scene
  24127. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24128. */
  24129. this.morphTargetManagers = new Array();
  24130. // Lens flares
  24131. /**
  24132. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24133. */
  24134. this.lensFlaresEnabled = true;
  24135. /**
  24136. * The list of lens flare system added to the scene
  24137. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24138. */
  24139. this.lensFlareSystems = new Array();
  24140. // Collisions
  24141. /**
  24142. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24143. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24144. */
  24145. this.collisionsEnabled = true;
  24146. /**
  24147. * Defines the gravity applied to this scene (used only for collisions)
  24148. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24149. */
  24150. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24151. // Postprocesses
  24152. /**
  24153. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24154. */
  24155. this.postProcessesEnabled = true;
  24156. /**
  24157. * The list of postprocesses added to the scene
  24158. */
  24159. this.postProcesses = new Array();
  24160. // Customs render targets
  24161. /**
  24162. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24163. */
  24164. this.renderTargetsEnabled = true;
  24165. /**
  24166. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24167. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24168. */
  24169. this.dumpNextRenderTargets = false;
  24170. /**
  24171. * The list of user defined render targets added to the scene
  24172. */
  24173. this.customRenderTargets = new Array();
  24174. /**
  24175. * Gets the list of meshes imported to the scene through SceneLoader
  24176. */
  24177. this.importedMeshesFiles = new Array();
  24178. // Probes
  24179. /**
  24180. * Gets or sets a boolean indicating if probes are enabled on this scene
  24181. */
  24182. this.probesEnabled = true;
  24183. /**
  24184. * The list of reflection probes added to the scene
  24185. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24186. */
  24187. this.reflectionProbes = new Array();
  24188. /** @hidden */
  24189. this._actionManagers = new Array();
  24190. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24191. // Procedural textures
  24192. /**
  24193. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24194. */
  24195. this.proceduralTexturesEnabled = true;
  24196. /**
  24197. * The list of procedural textures added to the scene
  24198. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24199. */
  24200. this.proceduralTextures = new Array();
  24201. /**
  24202. * The list of sound tracks added to the scene
  24203. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24204. */
  24205. this.soundTracks = new Array();
  24206. this._audioEnabled = true;
  24207. this._headphone = false;
  24208. // Performance counters
  24209. this._totalVertices = new BABYLON.PerfCounter();
  24210. /** @hidden */
  24211. this._activeIndices = new BABYLON.PerfCounter();
  24212. /** @hidden */
  24213. this._activeParticles = new BABYLON.PerfCounter();
  24214. /** @hidden */
  24215. this._activeBones = new BABYLON.PerfCounter();
  24216. this._animationTime = 0;
  24217. /**
  24218. * Gets or sets a general scale for animation speed
  24219. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24220. */
  24221. this.animationTimeScale = 1;
  24222. this._renderId = 0;
  24223. this._executeWhenReadyTimeoutId = -1;
  24224. this._intermediateRendering = false;
  24225. this._viewUpdateFlag = -1;
  24226. this._projectionUpdateFlag = -1;
  24227. this._alternateViewUpdateFlag = -1;
  24228. this._alternateProjectionUpdateFlag = -1;
  24229. /** @hidden */
  24230. this._toBeDisposed = new BABYLON.SmartArray(256);
  24231. this._activeRequests = new Array();
  24232. this._pendingData = new Array();
  24233. this._isDisposed = false;
  24234. /**
  24235. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24236. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24237. */
  24238. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24239. this._activeMeshes = new BABYLON.SmartArray(256);
  24240. this._processedMaterials = new BABYLON.SmartArray(256);
  24241. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24242. /** @hidden */
  24243. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24244. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24245. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24246. /** @hidden */
  24247. this._activeAnimatables = new Array();
  24248. this._transformMatrix = BABYLON.Matrix.Zero();
  24249. this._useAlternateCameraConfiguration = false;
  24250. this._alternateRendering = false;
  24251. /**
  24252. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24253. * This is useful if there are more lights that the maximum simulteanous authorized
  24254. */
  24255. this.requireLightSorting = false;
  24256. this._depthRenderer = {};
  24257. this._activeMeshesFrozen = false;
  24258. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24259. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24260. this._engine.scenes.push(this);
  24261. this._uid = null;
  24262. this._renderingManager = new BABYLON.RenderingManager(this);
  24263. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24264. if (BABYLON.OutlineRenderer) {
  24265. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24266. }
  24267. if (BABYLON.Tools.IsWindowObjectExist()) {
  24268. this.attachControl();
  24269. }
  24270. //simplification queue
  24271. if (BABYLON.SimplificationQueue) {
  24272. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24273. }
  24274. //collision coordinator initialization. For now legacy per default.
  24275. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24276. // Uniform Buffer
  24277. this._createUbo();
  24278. // Default Image processing definition.
  24279. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24280. }
  24281. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24282. /** The fog is deactivated */
  24283. get: function () {
  24284. return Scene._FOGMODE_NONE;
  24285. },
  24286. enumerable: true,
  24287. configurable: true
  24288. });
  24289. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24290. /** The fog density is following an exponential function */
  24291. get: function () {
  24292. return Scene._FOGMODE_EXP;
  24293. },
  24294. enumerable: true,
  24295. configurable: true
  24296. });
  24297. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24298. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24299. get: function () {
  24300. return Scene._FOGMODE_EXP2;
  24301. },
  24302. enumerable: true,
  24303. configurable: true
  24304. });
  24305. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24306. /** The fog density is following a linear function. */
  24307. get: function () {
  24308. return Scene._FOGMODE_LINEAR;
  24309. },
  24310. enumerable: true,
  24311. configurable: true
  24312. });
  24313. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24314. /**
  24315. * Texture used in all pbr material as the reflection texture.
  24316. * As in the majority of the scene they are the same (exception for multi room and so on),
  24317. * this is easier to reference from here than from all the materials.
  24318. */
  24319. get: function () {
  24320. return this._environmentTexture;
  24321. },
  24322. /**
  24323. * Texture used in all pbr material as the reflection texture.
  24324. * As in the majority of the scene they are the same (exception for multi room and so on),
  24325. * this is easier to set here than in all the materials.
  24326. */
  24327. set: function (value) {
  24328. if (this._environmentTexture === value) {
  24329. return;
  24330. }
  24331. this._environmentTexture = value;
  24332. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24333. },
  24334. enumerable: true,
  24335. configurable: true
  24336. });
  24337. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24338. /**
  24339. * Default image processing configuration used either in the rendering
  24340. * Forward main pass or through the imageProcessingPostProcess if present.
  24341. * As in the majority of the scene they are the same (exception for multi camera),
  24342. * this is easier to reference from here than from all the materials and post process.
  24343. *
  24344. * No setter as we it is a shared configuration, you can set the values instead.
  24345. */
  24346. get: function () {
  24347. return this._imageProcessingConfiguration;
  24348. },
  24349. enumerable: true,
  24350. configurable: true
  24351. });
  24352. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24353. get: function () {
  24354. return this._forceWireframe;
  24355. },
  24356. /**
  24357. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24358. */
  24359. set: function (value) {
  24360. if (this._forceWireframe === value) {
  24361. return;
  24362. }
  24363. this._forceWireframe = value;
  24364. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24365. },
  24366. enumerable: true,
  24367. configurable: true
  24368. });
  24369. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24370. get: function () {
  24371. return this._forcePointsCloud;
  24372. },
  24373. /**
  24374. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24375. */
  24376. set: function (value) {
  24377. if (this._forcePointsCloud === value) {
  24378. return;
  24379. }
  24380. this._forcePointsCloud = value;
  24381. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24382. },
  24383. enumerable: true,
  24384. configurable: true
  24385. });
  24386. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24387. /**
  24388. * Gets or sets the animation properties override
  24389. */
  24390. get: function () {
  24391. return this._animationPropertiesOverride;
  24392. },
  24393. set: function (value) {
  24394. this._animationPropertiesOverride = value;
  24395. },
  24396. enumerable: true,
  24397. configurable: true
  24398. });
  24399. Object.defineProperty(Scene.prototype, "onDispose", {
  24400. /** Sets a function to be executed when this scene is disposed. */
  24401. set: function (callback) {
  24402. if (this._onDisposeObserver) {
  24403. this.onDisposeObservable.remove(this._onDisposeObserver);
  24404. }
  24405. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24406. },
  24407. enumerable: true,
  24408. configurable: true
  24409. });
  24410. Object.defineProperty(Scene.prototype, "beforeRender", {
  24411. /** Sets a function to be executed before rendering this scene */
  24412. set: function (callback) {
  24413. if (this._onBeforeRenderObserver) {
  24414. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24415. }
  24416. if (callback) {
  24417. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24418. }
  24419. },
  24420. enumerable: true,
  24421. configurable: true
  24422. });
  24423. Object.defineProperty(Scene.prototype, "afterRender", {
  24424. /** Sets a function to be executed after rendering this scene */
  24425. set: function (callback) {
  24426. if (this._onAfterRenderObserver) {
  24427. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24428. }
  24429. if (callback) {
  24430. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24431. }
  24432. },
  24433. enumerable: true,
  24434. configurable: true
  24435. });
  24436. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24437. /** Sets a function to be executed before rendering a camera*/
  24438. set: function (callback) {
  24439. if (this._onBeforeCameraRenderObserver) {
  24440. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24441. }
  24442. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24448. /** Sets a function to be executed after rendering a camera*/
  24449. set: function (callback) {
  24450. if (this._onAfterCameraRenderObserver) {
  24451. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24452. }
  24453. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24454. },
  24455. enumerable: true,
  24456. configurable: true
  24457. });
  24458. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24459. /**
  24460. * Gets the gamepad manager associated with the scene
  24461. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24462. */
  24463. get: function () {
  24464. if (!this._gamepadManager) {
  24465. this._gamepadManager = new BABYLON.GamepadManager(this);
  24466. }
  24467. return this._gamepadManager;
  24468. },
  24469. enumerable: true,
  24470. configurable: true
  24471. });
  24472. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24473. /**
  24474. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24475. */
  24476. get: function () {
  24477. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24478. },
  24479. enumerable: true,
  24480. configurable: true
  24481. });
  24482. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24483. get: function () {
  24484. return this._useRightHandedSystem;
  24485. },
  24486. /**
  24487. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24488. */
  24489. set: function (value) {
  24490. if (this._useRightHandedSystem === value) {
  24491. return;
  24492. }
  24493. this._useRightHandedSystem = value;
  24494. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. /**
  24500. * Sets the step Id used by deterministic lock step
  24501. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24502. * @param newStepId defines the step Id
  24503. */
  24504. Scene.prototype.setStepId = function (newStepId) {
  24505. this._currentStepId = newStepId;
  24506. };
  24507. ;
  24508. /**
  24509. * Gets the step Id used by deterministic lock step
  24510. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24511. * @returns the step Id
  24512. */
  24513. Scene.prototype.getStepId = function () {
  24514. return this._currentStepId;
  24515. };
  24516. ;
  24517. /**
  24518. * Gets the internal step used by deterministic lock step
  24519. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24520. * @returns the internal step
  24521. */
  24522. Scene.prototype.getInternalStep = function () {
  24523. return this._currentInternalStep;
  24524. };
  24525. ;
  24526. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24527. get: function () {
  24528. return this._fogEnabled;
  24529. },
  24530. /**
  24531. * Gets or sets a boolean indicating if fog is enabled on this scene
  24532. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24533. */
  24534. set: function (value) {
  24535. if (this._fogEnabled === value) {
  24536. return;
  24537. }
  24538. this._fogEnabled = value;
  24539. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24540. },
  24541. enumerable: true,
  24542. configurable: true
  24543. });
  24544. Object.defineProperty(Scene.prototype, "fogMode", {
  24545. get: function () {
  24546. return this._fogMode;
  24547. },
  24548. /**
  24549. * Gets or sets the fog mode to use
  24550. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24551. */
  24552. set: function (value) {
  24553. if (this._fogMode === value) {
  24554. return;
  24555. }
  24556. this._fogMode = value;
  24557. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24563. get: function () {
  24564. return this._shadowsEnabled;
  24565. },
  24566. /**
  24567. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24568. */
  24569. set: function (value) {
  24570. if (this._shadowsEnabled === value) {
  24571. return;
  24572. }
  24573. this._shadowsEnabled = value;
  24574. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24580. get: function () {
  24581. return this._lightsEnabled;
  24582. },
  24583. /**
  24584. * Gets or sets a boolean indicating if lights are enabled on this scene
  24585. */
  24586. set: function (value) {
  24587. if (this._lightsEnabled === value) {
  24588. return;
  24589. }
  24590. this._lightsEnabled = value;
  24591. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24592. },
  24593. enumerable: true,
  24594. configurable: true
  24595. });
  24596. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24597. /** The default material used on meshes when no material is affected */
  24598. get: function () {
  24599. if (!this._defaultMaterial) {
  24600. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24601. }
  24602. return this._defaultMaterial;
  24603. },
  24604. /** The default material used on meshes when no material is affected */
  24605. set: function (value) {
  24606. this._defaultMaterial = value;
  24607. },
  24608. enumerable: true,
  24609. configurable: true
  24610. });
  24611. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24612. get: function () {
  24613. return this._texturesEnabled;
  24614. },
  24615. /**
  24616. * Gets or sets a boolean indicating if textures are enabled on this scene
  24617. */
  24618. set: function (value) {
  24619. if (this._texturesEnabled === value) {
  24620. return;
  24621. }
  24622. this._texturesEnabled = value;
  24623. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24629. get: function () {
  24630. return this._skeletonsEnabled;
  24631. },
  24632. /**
  24633. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24634. */
  24635. set: function (value) {
  24636. if (this._skeletonsEnabled === value) {
  24637. return;
  24638. }
  24639. this._skeletonsEnabled = value;
  24640. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24641. },
  24642. enumerable: true,
  24643. configurable: true
  24644. });
  24645. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24646. /**
  24647. * Gets the postprocess render pipeline manager
  24648. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24649. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24650. */
  24651. get: function () {
  24652. if (!this._postProcessRenderPipelineManager) {
  24653. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24654. }
  24655. return this._postProcessRenderPipelineManager;
  24656. },
  24657. enumerable: true,
  24658. configurable: true
  24659. });
  24660. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24661. /**
  24662. * Gets the main soundtrack associated with the scene
  24663. */
  24664. get: function () {
  24665. if (!this._mainSoundTrack) {
  24666. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24667. }
  24668. return this._mainSoundTrack;
  24669. },
  24670. enumerable: true,
  24671. configurable: true
  24672. });
  24673. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24674. /** @hidden */
  24675. get: function () {
  24676. return this._alternateRendering;
  24677. },
  24678. enumerable: true,
  24679. configurable: true
  24680. });
  24681. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24682. /**
  24683. * Gets the list of frustum planes (built from the active camera)
  24684. */
  24685. get: function () {
  24686. return this._frustumPlanes;
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24692. /**
  24693. * Gets the current geometry buffer associated to the scene.
  24694. */
  24695. get: function () {
  24696. return this._geometryBufferRenderer;
  24697. },
  24698. /**
  24699. * Sets the current geometry buffer for the scene.
  24700. */
  24701. set: function (geometryBufferRenderer) {
  24702. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24703. this._geometryBufferRenderer = geometryBufferRenderer;
  24704. }
  24705. },
  24706. enumerable: true,
  24707. configurable: true
  24708. });
  24709. Object.defineProperty(Scene.prototype, "debugLayer", {
  24710. /**
  24711. * Gets the debug layer (aka Inspector) associated with the scene
  24712. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24713. */
  24714. get: function () {
  24715. if (!this._debugLayer) {
  24716. this._debugLayer = new BABYLON.DebugLayer(this);
  24717. }
  24718. return this._debugLayer;
  24719. },
  24720. enumerable: true,
  24721. configurable: true
  24722. });
  24723. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24724. /**
  24725. * Gets a boolean indicating if collisions are processed on a web worker
  24726. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24727. */
  24728. get: function () {
  24729. return this._workerCollisions;
  24730. },
  24731. set: function (enabled) {
  24732. if (!BABYLON.CollisionCoordinatorLegacy) {
  24733. return;
  24734. }
  24735. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24736. this._workerCollisions = enabled;
  24737. if (this.collisionCoordinator) {
  24738. this.collisionCoordinator.destroy();
  24739. }
  24740. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24741. this.collisionCoordinator.init(this);
  24742. },
  24743. enumerable: true,
  24744. configurable: true
  24745. });
  24746. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24747. /**
  24748. * Gets the octree used to boost mesh selection (picking)
  24749. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24750. */
  24751. get: function () {
  24752. return this._selectionOctree;
  24753. },
  24754. enumerable: true,
  24755. configurable: true
  24756. });
  24757. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24758. /**
  24759. * Gets the mesh that is currently under the pointer
  24760. */
  24761. get: function () {
  24762. return this._pointerOverMesh;
  24763. },
  24764. enumerable: true,
  24765. configurable: true
  24766. });
  24767. Object.defineProperty(Scene.prototype, "pointerX", {
  24768. /**
  24769. * Gets the current on-screen X position of the pointer
  24770. */
  24771. get: function () {
  24772. return this._pointerX;
  24773. },
  24774. enumerable: true,
  24775. configurable: true
  24776. });
  24777. Object.defineProperty(Scene.prototype, "pointerY", {
  24778. /**
  24779. * Gets the current on-screen Y position of the pointer
  24780. */
  24781. get: function () {
  24782. return this._pointerY;
  24783. },
  24784. enumerable: true,
  24785. configurable: true
  24786. });
  24787. /**
  24788. * Gets the cached material (ie. the latest rendered one)
  24789. * @returns the cached material
  24790. */
  24791. Scene.prototype.getCachedMaterial = function () {
  24792. return this._cachedMaterial;
  24793. };
  24794. /**
  24795. * Gets the cached effect (ie. the latest rendered one)
  24796. * @returns the cached effect
  24797. */
  24798. Scene.prototype.getCachedEffect = function () {
  24799. return this._cachedEffect;
  24800. };
  24801. /**
  24802. * Gets the cached visibility state (ie. the latest rendered one)
  24803. * @returns the cached visibility state
  24804. */
  24805. Scene.prototype.getCachedVisibility = function () {
  24806. return this._cachedVisibility;
  24807. };
  24808. /**
  24809. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24810. * @param material defines the current material
  24811. * @param effect defines the current effect
  24812. * @param visibility defines the current visibility state
  24813. * @returns true if one parameter is not cached
  24814. */
  24815. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24816. if (visibility === void 0) { visibility = 1; }
  24817. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24818. };
  24819. /**
  24820. * Gets the bounding box renderer associated with the scene
  24821. * @returns a BoundingBoxRenderer
  24822. */
  24823. Scene.prototype.getBoundingBoxRenderer = function () {
  24824. if (!this._boundingBoxRenderer) {
  24825. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24826. }
  24827. return this._boundingBoxRenderer;
  24828. };
  24829. /**
  24830. * Gets the outline renderer associated with the scene
  24831. * @returns a OutlineRenderer
  24832. */
  24833. Scene.prototype.getOutlineRenderer = function () {
  24834. return this._outlineRenderer;
  24835. };
  24836. /**
  24837. * Gets the engine associated with the scene
  24838. * @returns an Engine
  24839. */
  24840. Scene.prototype.getEngine = function () {
  24841. return this._engine;
  24842. };
  24843. /**
  24844. * Gets the total number of vertices rendered per frame
  24845. * @returns the total number of vertices rendered per frame
  24846. */
  24847. Scene.prototype.getTotalVertices = function () {
  24848. return this._totalVertices.current;
  24849. };
  24850. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24851. /**
  24852. * Gets the performance counter for total vertices
  24853. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24854. */
  24855. get: function () {
  24856. return this._totalVertices;
  24857. },
  24858. enumerable: true,
  24859. configurable: true
  24860. });
  24861. /**
  24862. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24863. * @returns the total number of active indices rendered per frame
  24864. */
  24865. Scene.prototype.getActiveIndices = function () {
  24866. return this._activeIndices.current;
  24867. };
  24868. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24869. /**
  24870. * Gets the performance counter for active indices
  24871. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24872. */
  24873. get: function () {
  24874. return this._activeIndices;
  24875. },
  24876. enumerable: true,
  24877. configurable: true
  24878. });
  24879. /**
  24880. * Gets the total number of active particles rendered per frame
  24881. * @returns the total number of active particles rendered per frame
  24882. */
  24883. Scene.prototype.getActiveParticles = function () {
  24884. return this._activeParticles.current;
  24885. };
  24886. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24887. /**
  24888. * Gets the performance counter for active particles
  24889. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24890. */
  24891. get: function () {
  24892. return this._activeParticles;
  24893. },
  24894. enumerable: true,
  24895. configurable: true
  24896. });
  24897. /**
  24898. * Gets the total number of active bones rendered per frame
  24899. * @returns the total number of active bones rendered per frame
  24900. */
  24901. Scene.prototype.getActiveBones = function () {
  24902. return this._activeBones.current;
  24903. };
  24904. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24905. /**
  24906. * Gets the performance counter for active bones
  24907. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24908. */
  24909. get: function () {
  24910. return this._activeBones;
  24911. },
  24912. enumerable: true,
  24913. configurable: true
  24914. });
  24915. /** @hidden */
  24916. Scene.prototype.getInterFramePerfCounter = function () {
  24917. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24918. return 0;
  24919. };
  24920. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24921. /** @hidden */
  24922. get: function () {
  24923. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24924. return null;
  24925. },
  24926. enumerable: true,
  24927. configurable: true
  24928. });
  24929. /** @hidden */
  24930. Scene.prototype.getLastFrameDuration = function () {
  24931. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24932. return 0;
  24933. };
  24934. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24935. /** @hidden */
  24936. get: function () {
  24937. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24938. return null;
  24939. },
  24940. enumerable: true,
  24941. configurable: true
  24942. });
  24943. /** @hidden */
  24944. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24945. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24946. return 0;
  24947. };
  24948. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24949. /** @hidden */
  24950. get: function () {
  24951. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24952. return null;
  24953. },
  24954. enumerable: true,
  24955. configurable: true
  24956. });
  24957. /**
  24958. * Gets the array of active meshes
  24959. * @returns an array of AbstractMesh
  24960. */
  24961. Scene.prototype.getActiveMeshes = function () {
  24962. return this._activeMeshes;
  24963. };
  24964. /** @hidden */
  24965. Scene.prototype.getRenderTargetsDuration = function () {
  24966. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24967. return 0;
  24968. };
  24969. /** @hidden */
  24970. Scene.prototype.getRenderDuration = function () {
  24971. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24972. return 0;
  24973. };
  24974. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24975. /** @hidden */
  24976. get: function () {
  24977. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24978. return null;
  24979. },
  24980. enumerable: true,
  24981. configurable: true
  24982. });
  24983. /** @hidden */
  24984. Scene.prototype.getParticlesDuration = function () {
  24985. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24986. return 0;
  24987. };
  24988. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24989. /** @hidden */
  24990. get: function () {
  24991. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24992. return null;
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. /** @hidden */
  24998. Scene.prototype.getSpritesDuration = function () {
  24999. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25000. return 0;
  25001. };
  25002. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25003. /** @hidden */
  25004. get: function () {
  25005. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25006. return null;
  25007. },
  25008. enumerable: true,
  25009. configurable: true
  25010. });
  25011. /**
  25012. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25013. * @returns a number
  25014. */
  25015. Scene.prototype.getAnimationRatio = function () {
  25016. return this._animationRatio;
  25017. };
  25018. /**
  25019. * Gets an unique Id for the current frame
  25020. * @returns a number
  25021. */
  25022. Scene.prototype.getRenderId = function () {
  25023. return this._renderId;
  25024. };
  25025. /** Call this function if you want to manually increment the render Id*/
  25026. Scene.prototype.incrementRenderId = function () {
  25027. this._renderId++;
  25028. };
  25029. Scene.prototype._updatePointerPosition = function (evt) {
  25030. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25031. if (!canvasRect) {
  25032. return;
  25033. }
  25034. this._pointerX = evt.clientX - canvasRect.left;
  25035. this._pointerY = evt.clientY - canvasRect.top;
  25036. this._unTranslatedPointerX = this._pointerX;
  25037. this._unTranslatedPointerY = this._pointerY;
  25038. };
  25039. Scene.prototype._createUbo = function () {
  25040. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25041. this._sceneUbo.addUniform("viewProjection", 16);
  25042. this._sceneUbo.addUniform("view", 16);
  25043. };
  25044. Scene.prototype._createAlternateUbo = function () {
  25045. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25046. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25047. this._alternateSceneUbo.addUniform("view", 16);
  25048. };
  25049. // Pointers handling
  25050. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25051. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25052. if (result) {
  25053. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25054. }
  25055. return result;
  25056. };
  25057. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25058. if (pointerInfo.pickInfo) {
  25059. if (!pointerInfo.pickInfo.ray) {
  25060. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25061. }
  25062. }
  25063. };
  25064. /**
  25065. * Use this method to simulate a pointer move on a mesh
  25066. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25067. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25068. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25069. * @returns the current scene
  25070. */
  25071. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25072. var evt = new PointerEvent("pointermove", pointerEventInit);
  25073. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25074. return this;
  25075. }
  25076. return this._processPointerMove(pickResult, evt);
  25077. };
  25078. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25079. var canvas = this._engine.getRenderingCanvas();
  25080. if (!canvas) {
  25081. return this;
  25082. }
  25083. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25084. this.setPointerOverSprite(null);
  25085. this.setPointerOverMesh(pickResult.pickedMesh);
  25086. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25087. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25088. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25089. }
  25090. else {
  25091. canvas.style.cursor = this.hoverCursor;
  25092. }
  25093. }
  25094. else {
  25095. canvas.style.cursor = this.defaultCursor;
  25096. }
  25097. }
  25098. else {
  25099. this.setPointerOverMesh(null);
  25100. // Sprites
  25101. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25102. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25103. this.setPointerOverSprite(pickResult.pickedSprite);
  25104. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25105. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25106. }
  25107. else {
  25108. canvas.style.cursor = this.hoverCursor;
  25109. }
  25110. }
  25111. else {
  25112. this.setPointerOverSprite(null);
  25113. // Restore pointer
  25114. canvas.style.cursor = this.defaultCursor;
  25115. }
  25116. }
  25117. if (pickResult) {
  25118. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25119. if (this.onPointerMove) {
  25120. this.onPointerMove(evt, pickResult, type);
  25121. }
  25122. if (this.onPointerObservable.hasObservers()) {
  25123. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25124. this._setRayOnPointerInfo(pi);
  25125. this.onPointerObservable.notifyObservers(pi, type);
  25126. }
  25127. }
  25128. return this;
  25129. };
  25130. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25131. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25132. if (pickResult) {
  25133. pi.ray = pickResult.ray;
  25134. }
  25135. this.onPrePointerObservable.notifyObservers(pi, type);
  25136. if (pi.skipOnPointerObservable) {
  25137. return true;
  25138. }
  25139. else {
  25140. return false;
  25141. }
  25142. };
  25143. /**
  25144. * Use this method to simulate a pointer down on a mesh
  25145. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25146. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25147. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25148. * @returns the current scene
  25149. */
  25150. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25151. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25152. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25153. return this;
  25154. }
  25155. return this._processPointerDown(pickResult, evt);
  25156. };
  25157. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25158. var _this = this;
  25159. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25160. this._pickedDownMesh = pickResult.pickedMesh;
  25161. var actionManager = pickResult.pickedMesh.actionManager;
  25162. if (actionManager) {
  25163. if (actionManager.hasPickTriggers) {
  25164. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25165. switch (evt.button) {
  25166. case 0:
  25167. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25168. break;
  25169. case 1:
  25170. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25171. break;
  25172. case 2:
  25173. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25174. break;
  25175. }
  25176. }
  25177. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25178. window.setTimeout(function () {
  25179. 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);
  25180. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25181. if (_this._totalPointersPressed !== 0 &&
  25182. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25183. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25184. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25185. _this._startingPointerTime = 0;
  25186. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25187. }
  25188. }
  25189. }, Scene.LongPressDelay);
  25190. }
  25191. }
  25192. }
  25193. if (pickResult) {
  25194. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25195. if (this.onPointerDown) {
  25196. this.onPointerDown(evt, pickResult, type);
  25197. }
  25198. if (this.onPointerObservable.hasObservers()) {
  25199. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25200. this._setRayOnPointerInfo(pi);
  25201. this.onPointerObservable.notifyObservers(pi, type);
  25202. }
  25203. }
  25204. return this;
  25205. };
  25206. /**
  25207. * Use this method to simulate a pointer up on a mesh
  25208. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25209. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25210. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25211. * @returns the current scene
  25212. */
  25213. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25214. var evt = new PointerEvent("pointerup", pointerEventInit);
  25215. var clickInfo = new ClickInfo();
  25216. clickInfo.singleClick = true;
  25217. clickInfo.ignore = true;
  25218. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25219. return this;
  25220. }
  25221. return this._processPointerUp(pickResult, evt, clickInfo);
  25222. };
  25223. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25224. if (pickResult && pickResult && pickResult.pickedMesh) {
  25225. this._pickedUpMesh = pickResult.pickedMesh;
  25226. if (this._pickedDownMesh === this._pickedUpMesh) {
  25227. if (this.onPointerPick) {
  25228. this.onPointerPick(evt, pickResult);
  25229. }
  25230. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25231. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25232. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25233. this._setRayOnPointerInfo(pi);
  25234. this.onPointerObservable.notifyObservers(pi, type_1);
  25235. }
  25236. }
  25237. if (pickResult.pickedMesh.actionManager) {
  25238. if (clickInfo.ignore) {
  25239. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25240. }
  25241. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25242. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25243. }
  25244. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25245. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25246. }
  25247. }
  25248. }
  25249. if (this._pickedDownMesh &&
  25250. this._pickedDownMesh.actionManager &&
  25251. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25252. this._pickedDownMesh !== this._pickedUpMesh) {
  25253. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25254. }
  25255. var type = BABYLON.PointerEventTypes.POINTERUP;
  25256. if (this.onPointerObservable.hasObservers()) {
  25257. if (!clickInfo.ignore) {
  25258. if (!clickInfo.hasSwiped) {
  25259. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25260. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25261. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25262. this._setRayOnPointerInfo(pi);
  25263. this.onPointerObservable.notifyObservers(pi, type_2);
  25264. }
  25265. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25266. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25267. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25268. this._setRayOnPointerInfo(pi);
  25269. this.onPointerObservable.notifyObservers(pi, type_3);
  25270. }
  25271. }
  25272. }
  25273. else {
  25274. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25275. this._setRayOnPointerInfo(pi);
  25276. this.onPointerObservable.notifyObservers(pi, type);
  25277. }
  25278. }
  25279. if (this.onPointerUp) {
  25280. this.onPointerUp(evt, pickResult, type);
  25281. }
  25282. return this;
  25283. };
  25284. /**
  25285. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25286. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25287. * @returns true if the pointer was captured
  25288. */
  25289. Scene.prototype.isPointerCaptured = function (pointerId) {
  25290. if (pointerId === void 0) { pointerId = 0; }
  25291. return this._pointerCaptures[pointerId];
  25292. };
  25293. /**
  25294. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25295. * @param attachUp defines if you want to attach events to pointerup
  25296. * @param attachDown defines if you want to attach events to pointerdown
  25297. * @param attachMove defines if you want to attach events to pointermove
  25298. */
  25299. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25300. var _this = this;
  25301. if (attachUp === void 0) { attachUp = true; }
  25302. if (attachDown === void 0) { attachDown = true; }
  25303. if (attachMove === void 0) { attachMove = true; }
  25304. this._initActionManager = function (act, clickInfo) {
  25305. if (!_this._meshPickProceed) {
  25306. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25307. _this._currentPickResult = pickResult;
  25308. if (pickResult) {
  25309. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25310. }
  25311. _this._meshPickProceed = true;
  25312. }
  25313. return act;
  25314. };
  25315. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25316. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25317. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25318. btn !== _this._previousButtonPressed) {
  25319. _this._doubleClickOccured = false;
  25320. clickInfo.singleClick = true;
  25321. clickInfo.ignore = false;
  25322. cb(clickInfo, _this._currentPickResult);
  25323. }
  25324. };
  25325. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25326. var clickInfo = new ClickInfo();
  25327. _this._currentPickResult = null;
  25328. var act = null;
  25329. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25330. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25331. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25332. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25333. act = _this._initActionManager(act, clickInfo);
  25334. if (act)
  25335. checkPicking = act.hasPickTriggers;
  25336. }
  25337. if (checkPicking) {
  25338. var btn = evt.button;
  25339. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25340. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25341. if (!clickInfo.hasSwiped) {
  25342. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25343. if (!checkSingleClickImmediately) {
  25344. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25345. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25346. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25347. act = _this._initActionManager(act, clickInfo);
  25348. if (act)
  25349. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25350. }
  25351. }
  25352. if (checkSingleClickImmediately) {
  25353. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25354. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25355. btn !== _this._previousButtonPressed) {
  25356. clickInfo.singleClick = true;
  25357. cb(clickInfo, _this._currentPickResult);
  25358. }
  25359. }
  25360. // at least one double click is required to be check and exclusive double click is enabled
  25361. else {
  25362. // wait that no double click has been raised during the double click delay
  25363. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25364. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25365. }
  25366. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25367. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25368. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25369. act = _this._initActionManager(act, clickInfo);
  25370. if (act)
  25371. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25372. }
  25373. if (checkDoubleClick) {
  25374. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25375. if (btn === _this._previousButtonPressed &&
  25376. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25377. !_this._doubleClickOccured) {
  25378. // pointer has not moved for 2 clicks, it's a double click
  25379. if (!clickInfo.hasSwiped &&
  25380. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25381. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25382. _this._previousStartingPointerTime = 0;
  25383. _this._doubleClickOccured = true;
  25384. clickInfo.doubleClick = true;
  25385. clickInfo.ignore = false;
  25386. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25387. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25388. }
  25389. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25390. cb(clickInfo, _this._currentPickResult);
  25391. }
  25392. // if the two successive clicks are too far, it's just two simple clicks
  25393. else {
  25394. _this._doubleClickOccured = false;
  25395. _this._previousStartingPointerTime = _this._startingPointerTime;
  25396. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25397. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25398. _this._previousButtonPressed = btn;
  25399. if (Scene.ExclusiveDoubleClickMode) {
  25400. if (_this._previousDelayedSimpleClickTimeout) {
  25401. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25402. }
  25403. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25404. cb(clickInfo, _this._previousPickResult);
  25405. }
  25406. else {
  25407. cb(clickInfo, _this._currentPickResult);
  25408. }
  25409. }
  25410. }
  25411. // just the first click of the double has been raised
  25412. else {
  25413. _this._doubleClickOccured = false;
  25414. _this._previousStartingPointerTime = _this._startingPointerTime;
  25415. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25416. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25417. _this._previousButtonPressed = btn;
  25418. }
  25419. }
  25420. }
  25421. }
  25422. clickInfo.ignore = true;
  25423. cb(clickInfo, _this._currentPickResult);
  25424. };
  25425. this._spritePredicate = function (sprite) {
  25426. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25427. };
  25428. this._onPointerMove = function (evt) {
  25429. _this._updatePointerPosition(evt);
  25430. // PreObservable support
  25431. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25432. return;
  25433. }
  25434. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25435. return;
  25436. }
  25437. if (!_this.pointerMovePredicate) {
  25438. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25439. }
  25440. // Meshes
  25441. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25442. _this._processPointerMove(pickResult, evt);
  25443. };
  25444. this._onPointerDown = function (evt) {
  25445. _this._totalPointersPressed++;
  25446. _this._pickedDownMesh = null;
  25447. _this._meshPickProceed = false;
  25448. _this._updatePointerPosition(evt);
  25449. if (_this.preventDefaultOnPointerDown && canvas) {
  25450. evt.preventDefault();
  25451. canvas.focus();
  25452. }
  25453. // PreObservable support
  25454. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25455. return;
  25456. }
  25457. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25458. return;
  25459. }
  25460. _this._pointerCaptures[evt.pointerId] = true;
  25461. _this._startingPointerPosition.x = _this._pointerX;
  25462. _this._startingPointerPosition.y = _this._pointerY;
  25463. _this._startingPointerTime = Date.now();
  25464. if (!_this.pointerDownPredicate) {
  25465. _this.pointerDownPredicate = function (mesh) {
  25466. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25467. };
  25468. }
  25469. // Meshes
  25470. _this._pickedDownMesh = null;
  25471. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25472. _this._processPointerDown(pickResult, evt);
  25473. // Sprites
  25474. _this._pickedDownSprite = null;
  25475. if (_this.spriteManagers.length > 0) {
  25476. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25477. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25478. if (pickResult.pickedSprite.actionManager) {
  25479. _this._pickedDownSprite = pickResult.pickedSprite;
  25480. switch (evt.button) {
  25481. case 0:
  25482. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25483. break;
  25484. case 1:
  25485. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25486. break;
  25487. case 2:
  25488. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25489. break;
  25490. }
  25491. if (pickResult.pickedSprite.actionManager) {
  25492. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25493. }
  25494. }
  25495. }
  25496. }
  25497. };
  25498. this._onPointerUp = function (evt) {
  25499. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25500. return; // So we need to test it the pointer down was pressed before.
  25501. }
  25502. _this._totalPointersPressed--;
  25503. _this._pickedUpMesh = null;
  25504. _this._meshPickProceed = false;
  25505. _this._updatePointerPosition(evt);
  25506. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25507. // PreObservable support
  25508. if (_this.onPrePointerObservable.hasObservers()) {
  25509. if (!clickInfo.ignore) {
  25510. if (!clickInfo.hasSwiped) {
  25511. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25512. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25513. return;
  25514. }
  25515. }
  25516. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25517. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25518. return;
  25519. }
  25520. }
  25521. }
  25522. }
  25523. else {
  25524. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25525. return;
  25526. }
  25527. }
  25528. }
  25529. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25530. return;
  25531. }
  25532. _this._pointerCaptures[evt.pointerId] = false;
  25533. if (!_this.pointerUpPredicate) {
  25534. _this.pointerUpPredicate = function (mesh) {
  25535. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25536. };
  25537. }
  25538. // Meshes
  25539. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25540. _this._initActionManager(null, clickInfo);
  25541. }
  25542. if (!pickResult) {
  25543. pickResult = _this._currentPickResult;
  25544. }
  25545. _this._processPointerUp(pickResult, evt, clickInfo);
  25546. // Sprites
  25547. if (!clickInfo.ignore) {
  25548. if (_this.spriteManagers.length > 0) {
  25549. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25550. if (spritePickResult) {
  25551. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25552. if (spritePickResult.pickedSprite.actionManager) {
  25553. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25554. if (spritePickResult.pickedSprite.actionManager) {
  25555. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25556. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25557. }
  25558. }
  25559. }
  25560. }
  25561. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25562. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25563. }
  25564. }
  25565. }
  25566. }
  25567. _this._previousPickResult = _this._currentPickResult;
  25568. });
  25569. };
  25570. this._onKeyDown = function (evt) {
  25571. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25572. if (_this.onPreKeyboardObservable.hasObservers()) {
  25573. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25574. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25575. if (pi.skipOnPointerObservable) {
  25576. return;
  25577. }
  25578. }
  25579. if (_this.onKeyboardObservable.hasObservers()) {
  25580. var pi = new BABYLON.KeyboardInfo(type, evt);
  25581. _this.onKeyboardObservable.notifyObservers(pi, type);
  25582. }
  25583. if (_this.actionManager) {
  25584. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25585. }
  25586. };
  25587. this._onKeyUp = function (evt) {
  25588. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25589. if (_this.onPreKeyboardObservable.hasObservers()) {
  25590. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25591. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25592. if (pi.skipOnPointerObservable) {
  25593. return;
  25594. }
  25595. }
  25596. if (_this.onKeyboardObservable.hasObservers()) {
  25597. var pi = new BABYLON.KeyboardInfo(type, evt);
  25598. _this.onKeyboardObservable.notifyObservers(pi, type);
  25599. }
  25600. if (_this.actionManager) {
  25601. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25602. }
  25603. };
  25604. var engine = this.getEngine();
  25605. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25606. if (!canvas) {
  25607. return;
  25608. }
  25609. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25610. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25611. });
  25612. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25613. if (!canvas) {
  25614. return;
  25615. }
  25616. canvas.removeEventListener("keydown", _this._onKeyDown);
  25617. canvas.removeEventListener("keyup", _this._onKeyUp);
  25618. });
  25619. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25620. var canvas = this._engine.getRenderingCanvas();
  25621. if (!canvas) {
  25622. return;
  25623. }
  25624. if (attachMove) {
  25625. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25626. // Wheel
  25627. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25628. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25629. }
  25630. if (attachDown) {
  25631. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25632. }
  25633. if (attachUp) {
  25634. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25635. }
  25636. canvas.tabIndex = 1;
  25637. };
  25638. /** Detaches all event handlers*/
  25639. Scene.prototype.detachControl = function () {
  25640. var engine = this.getEngine();
  25641. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25642. var canvas = engine.getRenderingCanvas();
  25643. if (!canvas) {
  25644. return;
  25645. }
  25646. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25647. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25648. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25649. if (this._onCanvasBlurObserver) {
  25650. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25651. }
  25652. if (this._onCanvasFocusObserver) {
  25653. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25654. }
  25655. // Wheel
  25656. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25657. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25658. // Keyboard
  25659. canvas.removeEventListener("keydown", this._onKeyDown);
  25660. canvas.removeEventListener("keyup", this._onKeyUp);
  25661. // Observables
  25662. this.onKeyboardObservable.clear();
  25663. this.onPreKeyboardObservable.clear();
  25664. this.onPointerObservable.clear();
  25665. this.onPrePointerObservable.clear();
  25666. };
  25667. /**
  25668. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25669. * Delay loaded resources are not taking in account
  25670. * @return true if all required resources are ready
  25671. */
  25672. Scene.prototype.isReady = function () {
  25673. if (this._isDisposed) {
  25674. return false;
  25675. }
  25676. if (this._pendingData.length > 0) {
  25677. return false;
  25678. }
  25679. var index;
  25680. var engine = this.getEngine();
  25681. // Geometries
  25682. for (index = 0; index < this._geometries.length; index++) {
  25683. var geometry = this._geometries[index];
  25684. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25685. return false;
  25686. }
  25687. }
  25688. // Meshes
  25689. for (index = 0; index < this.meshes.length; index++) {
  25690. var mesh = this.meshes[index];
  25691. if (!mesh.isEnabled()) {
  25692. continue;
  25693. }
  25694. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25695. continue;
  25696. }
  25697. if (!mesh.isReady(true)) {
  25698. return false;
  25699. }
  25700. // Effect layers
  25701. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25702. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25703. var layer = _a[_i];
  25704. if (!layer.hasMesh(mesh)) {
  25705. continue;
  25706. }
  25707. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25708. var subMesh = _c[_b];
  25709. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25710. return false;
  25711. }
  25712. }
  25713. }
  25714. }
  25715. // Post-processes
  25716. if (this.activeCameras && this.activeCameras.length > 0) {
  25717. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25718. var camera = _e[_d];
  25719. if (!camera.isReady(true)) {
  25720. return false;
  25721. }
  25722. }
  25723. }
  25724. else if (this.activeCamera) {
  25725. if (!this.activeCamera.isReady(true)) {
  25726. return false;
  25727. }
  25728. }
  25729. // Particles
  25730. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25731. var particleSystem = _g[_f];
  25732. if (!particleSystem.isReady()) {
  25733. return false;
  25734. }
  25735. }
  25736. return true;
  25737. };
  25738. /** Resets all cached information relative to material (including effect and visibility) */
  25739. Scene.prototype.resetCachedMaterial = function () {
  25740. this._cachedMaterial = null;
  25741. this._cachedEffect = null;
  25742. this._cachedVisibility = null;
  25743. };
  25744. /**
  25745. * Registers a function to be called before every frame render
  25746. * @param func defines the function to register
  25747. */
  25748. Scene.prototype.registerBeforeRender = function (func) {
  25749. this.onBeforeRenderObservable.add(func);
  25750. };
  25751. /**
  25752. * Unregisters a function called before every frame render
  25753. * @param func defines the function to unregister
  25754. */
  25755. Scene.prototype.unregisterBeforeRender = function (func) {
  25756. this.onBeforeRenderObservable.removeCallback(func);
  25757. };
  25758. /**
  25759. * Registers a function to be called after every frame render
  25760. * @param func defines the function to register
  25761. */
  25762. Scene.prototype.registerAfterRender = function (func) {
  25763. this.onAfterRenderObservable.add(func);
  25764. };
  25765. /**
  25766. * Unregisters a function called after every frame render
  25767. * @param func defines the function to unregister
  25768. */
  25769. Scene.prototype.unregisterAfterRender = function (func) {
  25770. this.onAfterRenderObservable.removeCallback(func);
  25771. };
  25772. Scene.prototype._executeOnceBeforeRender = function (func) {
  25773. var _this = this;
  25774. var execFunc = function () {
  25775. func();
  25776. setTimeout(function () {
  25777. _this.unregisterBeforeRender(execFunc);
  25778. });
  25779. };
  25780. this.registerBeforeRender(execFunc);
  25781. };
  25782. /**
  25783. * The provided function will run before render once and will be disposed afterwards.
  25784. * A timeout delay can be provided so that the function will be executed in N ms.
  25785. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25786. * @param func The function to be executed.
  25787. * @param timeout optional delay in ms
  25788. */
  25789. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25790. var _this = this;
  25791. if (timeout !== undefined) {
  25792. setTimeout(function () {
  25793. _this._executeOnceBeforeRender(func);
  25794. }, timeout);
  25795. }
  25796. else {
  25797. this._executeOnceBeforeRender(func);
  25798. }
  25799. };
  25800. /** @hidden */
  25801. Scene.prototype._addPendingData = function (data) {
  25802. this._pendingData.push(data);
  25803. };
  25804. /** @hidden */
  25805. Scene.prototype._removePendingData = function (data) {
  25806. var wasLoading = this.isLoading;
  25807. var index = this._pendingData.indexOf(data);
  25808. if (index !== -1) {
  25809. this._pendingData.splice(index, 1);
  25810. }
  25811. if (wasLoading && !this.isLoading) {
  25812. this.onDataLoadedObservable.notifyObservers(this);
  25813. }
  25814. };
  25815. /**
  25816. * Returns the number of items waiting to be loaded
  25817. * @returns the number of items waiting to be loaded
  25818. */
  25819. Scene.prototype.getWaitingItemsCount = function () {
  25820. return this._pendingData.length;
  25821. };
  25822. Object.defineProperty(Scene.prototype, "isLoading", {
  25823. /**
  25824. * Returns a boolean indicating if the scene is still loading data
  25825. */
  25826. get: function () {
  25827. return this._pendingData.length > 0;
  25828. },
  25829. enumerable: true,
  25830. configurable: true
  25831. });
  25832. /**
  25833. * Registers a function to be executed when the scene is ready
  25834. * @param {Function} func - the function to be executed
  25835. */
  25836. Scene.prototype.executeWhenReady = function (func) {
  25837. var _this = this;
  25838. this.onReadyObservable.add(func);
  25839. if (this._executeWhenReadyTimeoutId !== -1) {
  25840. return;
  25841. }
  25842. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25843. _this._checkIsReady();
  25844. }, 150);
  25845. };
  25846. /**
  25847. * Returns a promise that resolves when the scene is ready
  25848. * @returns A promise that resolves when the scene is ready
  25849. */
  25850. Scene.prototype.whenReadyAsync = function () {
  25851. var _this = this;
  25852. return new Promise(function (resolve) {
  25853. _this.executeWhenReady(function () {
  25854. resolve();
  25855. });
  25856. });
  25857. };
  25858. /** @hidden */
  25859. Scene.prototype._checkIsReady = function () {
  25860. var _this = this;
  25861. if (this.isReady()) {
  25862. this.onReadyObservable.notifyObservers(this);
  25863. this.onReadyObservable.clear();
  25864. this._executeWhenReadyTimeoutId = -1;
  25865. return;
  25866. }
  25867. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25868. _this._checkIsReady();
  25869. }, 150);
  25870. };
  25871. // Animations
  25872. /**
  25873. * Will start the animation sequence of a given target
  25874. * @param target defines the target
  25875. * @param from defines from which frame should animation start
  25876. * @param to defines until which frame should animation run.
  25877. * @param weight defines the weight to apply to the animation (1.0 by default)
  25878. * @param loop defines if the animation loops
  25879. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25880. * @param onAnimationEnd defines the function to be executed when the animation ends
  25881. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25882. * @returns the animatable object created for this animation
  25883. */
  25884. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25885. if (weight === void 0) { weight = 1.0; }
  25886. if (speedRatio === void 0) { speedRatio = 1.0; }
  25887. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25888. returnedAnimatable.weight = weight;
  25889. return returnedAnimatable;
  25890. };
  25891. /**
  25892. * Will start the animation sequence of a given target
  25893. * @param target defines the target
  25894. * @param from defines from which frame should animation start
  25895. * @param to defines until which frame should animation run.
  25896. * @param loop defines if the animation loops
  25897. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25898. * @param onAnimationEnd defines the function to be executed when the animation ends
  25899. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25900. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25901. * @returns the animatable object created for this animation
  25902. */
  25903. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25904. if (speedRatio === void 0) { speedRatio = 1.0; }
  25905. if (stopCurrent === void 0) { stopCurrent = true; }
  25906. if (from > to && speedRatio > 0) {
  25907. speedRatio *= -1;
  25908. }
  25909. if (stopCurrent) {
  25910. this.stopAnimation(target);
  25911. }
  25912. if (!animatable) {
  25913. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25914. }
  25915. // Local animations
  25916. if (target.animations) {
  25917. animatable.appendAnimations(target, target.animations);
  25918. }
  25919. // Children animations
  25920. if (target.getAnimatables) {
  25921. var animatables = target.getAnimatables();
  25922. for (var index = 0; index < animatables.length; index++) {
  25923. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25924. }
  25925. }
  25926. animatable.reset();
  25927. return animatable;
  25928. };
  25929. /**
  25930. * Begin a new animation on a given node
  25931. * @param target defines the target where the animation will take place
  25932. * @param animations defines the list of animations to start
  25933. * @param from defines the initial value
  25934. * @param to defines the final value
  25935. * @param loop defines if you want animation to loop (off by default)
  25936. * @param speedRatio defines the speed ratio to apply to all animations
  25937. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25938. * @returns the list of created animatables
  25939. */
  25940. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25941. if (speedRatio === undefined) {
  25942. speedRatio = 1.0;
  25943. }
  25944. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25945. return animatable;
  25946. };
  25947. /**
  25948. * Begin a new animation on a given node and its hierarchy
  25949. * @param target defines the root node where the animation will take place
  25950. * @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.
  25951. * @param animations defines the list of animations to start
  25952. * @param from defines the initial value
  25953. * @param to defines the final value
  25954. * @param loop defines if you want animation to loop (off by default)
  25955. * @param speedRatio defines the speed ratio to apply to all animations
  25956. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25957. * @returns the list of animatables created for all nodes
  25958. */
  25959. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25960. var children = target.getDescendants(directDescendantsOnly);
  25961. var result = [];
  25962. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25963. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25964. var child = children_1[_i];
  25965. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25966. }
  25967. return result;
  25968. };
  25969. /**
  25970. * Gets the animatable associated with a specific target
  25971. * @param target defines the target of the animatable
  25972. * @returns the required animatable if found
  25973. */
  25974. Scene.prototype.getAnimatableByTarget = function (target) {
  25975. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25976. if (this._activeAnimatables[index].target === target) {
  25977. return this._activeAnimatables[index];
  25978. }
  25979. }
  25980. return null;
  25981. };
  25982. /**
  25983. * Gets all animatables associated with a given target
  25984. * @param target defines the target to look animatables for
  25985. * @returns an array of Animatables
  25986. */
  25987. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25988. var result = [];
  25989. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25990. if (this._activeAnimatables[index].target === target) {
  25991. result.push(this._activeAnimatables[index]);
  25992. }
  25993. }
  25994. return result;
  25995. };
  25996. Object.defineProperty(Scene.prototype, "animatables", {
  25997. /**
  25998. * Gets all animatable attached to the scene
  25999. */
  26000. get: function () {
  26001. return this._activeAnimatables;
  26002. },
  26003. enumerable: true,
  26004. configurable: true
  26005. });
  26006. /**
  26007. * Will stop the animation of the given target
  26008. * @param target - the target
  26009. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26010. */
  26011. Scene.prototype.stopAnimation = function (target, animationName) {
  26012. var animatables = this.getAllAnimatablesByTarget(target);
  26013. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26014. var animatable = animatables_1[_i];
  26015. animatable.stop(animationName);
  26016. }
  26017. };
  26018. /**
  26019. * Stops and removes all animations that have been applied to the scene
  26020. */
  26021. Scene.prototype.stopAllAnimations = function () {
  26022. if (this._activeAnimatables) {
  26023. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26024. this._activeAnimatables[i].stop();
  26025. }
  26026. this._activeAnimatables = [];
  26027. }
  26028. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26029. var group = _a[_i];
  26030. group.stop();
  26031. }
  26032. };
  26033. Scene.prototype._animate = function () {
  26034. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26035. return;
  26036. }
  26037. // Getting time
  26038. var now = BABYLON.Tools.Now;
  26039. if (!this._animationTimeLast) {
  26040. if (this._pendingData.length > 0) {
  26041. return;
  26042. }
  26043. this._animationTimeLast = now;
  26044. }
  26045. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26046. this._animationTime += deltaTime;
  26047. this._animationTimeLast = now;
  26048. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26049. this._activeAnimatables[index]._animate(this._animationTime);
  26050. }
  26051. // Late animation bindings
  26052. this._processLateAnimationBindings();
  26053. };
  26054. /** @hidden */
  26055. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26056. var target = runtimeAnimation.target;
  26057. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26058. if (!target._lateAnimationHolders) {
  26059. target._lateAnimationHolders = {};
  26060. }
  26061. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26062. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26063. totalWeight: 0,
  26064. animations: [],
  26065. originalValue: originalValue
  26066. };
  26067. }
  26068. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26069. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26070. };
  26071. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26072. var normalizer = 1.0;
  26073. var finalPosition = BABYLON.Tmp.Vector3[0];
  26074. var finalScaling = BABYLON.Tmp.Vector3[1];
  26075. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26076. var startIndex = 0;
  26077. var originalAnimation = holder.animations[0];
  26078. var originalValue = holder.originalValue;
  26079. var scale = 1;
  26080. if (holder.totalWeight < 1.0) {
  26081. // We need to mix the original value in
  26082. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26083. scale = 1.0 - holder.totalWeight;
  26084. }
  26085. else {
  26086. startIndex = 1;
  26087. // We need to normalize the weights
  26088. normalizer = holder.totalWeight;
  26089. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26090. scale = originalAnimation.weight / normalizer;
  26091. if (scale == 1) {
  26092. return originalAnimation.currentValue;
  26093. }
  26094. }
  26095. finalScaling.scaleInPlace(scale);
  26096. finalPosition.scaleInPlace(scale);
  26097. finalQuaternion.scaleInPlace(scale);
  26098. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26099. var runtimeAnimation = holder.animations[animIndex];
  26100. var scale = runtimeAnimation.weight / normalizer;
  26101. var currentPosition = BABYLON.Tmp.Vector3[2];
  26102. var currentScaling = BABYLON.Tmp.Vector3[3];
  26103. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26104. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26105. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26106. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26107. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26108. }
  26109. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26110. return originalAnimation._workValue;
  26111. };
  26112. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26113. var originalAnimation = holder.animations[0];
  26114. var originalValue = holder.originalValue;
  26115. if (holder.animations.length === 1) {
  26116. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26117. }
  26118. var normalizer = 1.0;
  26119. var quaternions;
  26120. var weights;
  26121. if (holder.totalWeight < 1.0) {
  26122. var scale = 1.0 - holder.totalWeight;
  26123. quaternions = [];
  26124. weights = [];
  26125. quaternions.push(originalValue);
  26126. weights.push(scale);
  26127. }
  26128. else {
  26129. if (holder.animations.length === 2) { // Slerp as soon as we can
  26130. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26131. }
  26132. quaternions = [];
  26133. weights = [];
  26134. normalizer = holder.totalWeight;
  26135. }
  26136. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26137. var runtimeAnimation = holder.animations[animIndex];
  26138. quaternions.push(runtimeAnimation.currentValue);
  26139. weights.push(runtimeAnimation.weight / normalizer);
  26140. }
  26141. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26142. var cumulativeAmount = 0;
  26143. var cumulativeQuaternion = null;
  26144. for (var index = 0; index < quaternions.length;) {
  26145. if (!cumulativeQuaternion) {
  26146. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26147. cumulativeAmount = weights[index] + weights[index + 1];
  26148. index += 2;
  26149. continue;
  26150. }
  26151. cumulativeAmount += weights[index];
  26152. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26153. index++;
  26154. }
  26155. return cumulativeQuaternion;
  26156. };
  26157. Scene.prototype._processLateAnimationBindings = function () {
  26158. if (!this._registeredForLateAnimationBindings.length) {
  26159. return;
  26160. }
  26161. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26162. var target = this._registeredForLateAnimationBindings.data[index];
  26163. for (var path in target._lateAnimationHolders) {
  26164. var holder = target._lateAnimationHolders[path];
  26165. var originalAnimation = holder.animations[0];
  26166. var originalValue = holder.originalValue;
  26167. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26168. var finalValue = void 0;
  26169. if (matrixDecomposeMode) {
  26170. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26171. }
  26172. else {
  26173. var quaternionMode = originalValue.w !== undefined;
  26174. if (quaternionMode) {
  26175. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26176. }
  26177. else {
  26178. var startIndex = 0;
  26179. var normalizer = 1.0;
  26180. if (holder.totalWeight < 1.0) {
  26181. // We need to mix the original value in
  26182. if (originalValue.scale) {
  26183. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26184. }
  26185. else {
  26186. finalValue = originalValue * (1.0 - holder.totalWeight);
  26187. }
  26188. }
  26189. else {
  26190. // We need to normalize the weights
  26191. normalizer = holder.totalWeight;
  26192. var scale_1 = originalAnimation.weight / normalizer;
  26193. if (scale_1 !== 1) {
  26194. if (originalAnimation.currentValue.scale) {
  26195. finalValue = originalAnimation.currentValue.scale(scale_1);
  26196. }
  26197. else {
  26198. finalValue = originalAnimation.currentValue * scale_1;
  26199. }
  26200. }
  26201. else {
  26202. finalValue = originalAnimation.currentValue;
  26203. }
  26204. startIndex = 1;
  26205. }
  26206. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26207. var runtimeAnimation = holder.animations[animIndex];
  26208. var scale = runtimeAnimation.weight / normalizer;
  26209. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26210. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26211. }
  26212. else {
  26213. finalValue += runtimeAnimation.currentValue * scale;
  26214. }
  26215. }
  26216. }
  26217. }
  26218. target[path] = finalValue;
  26219. }
  26220. target._lateAnimationHolders = {};
  26221. }
  26222. this._registeredForLateAnimationBindings.reset();
  26223. };
  26224. // Matrix
  26225. /** @hidden */
  26226. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26227. this._useAlternateCameraConfiguration = active;
  26228. };
  26229. /**
  26230. * Gets the current view matrix
  26231. * @returns a Matrix
  26232. */
  26233. Scene.prototype.getViewMatrix = function () {
  26234. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26235. };
  26236. /**
  26237. * Gets the current projection matrix
  26238. * @returns a Matrix
  26239. */
  26240. Scene.prototype.getProjectionMatrix = function () {
  26241. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26242. };
  26243. /**
  26244. * Gets the current transform matrix
  26245. * @returns a Matrix made of View * Projection
  26246. */
  26247. Scene.prototype.getTransformMatrix = function () {
  26248. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26249. };
  26250. /**
  26251. * Sets the current transform matrix
  26252. * @param view defines the View matrix to use
  26253. * @param projection defines the Projection matrix to use
  26254. */
  26255. Scene.prototype.setTransformMatrix = function (view, projection) {
  26256. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26257. return;
  26258. }
  26259. this._viewUpdateFlag = view.updateFlag;
  26260. this._projectionUpdateFlag = projection.updateFlag;
  26261. this._viewMatrix = view;
  26262. this._projectionMatrix = projection;
  26263. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26264. // Update frustum
  26265. if (!this._frustumPlanes) {
  26266. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26267. }
  26268. else {
  26269. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26270. }
  26271. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26272. var otherCamera = this.activeCamera._alternateCamera;
  26273. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26274. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26275. }
  26276. if (this._sceneUbo.useUbo) {
  26277. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26278. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26279. this._sceneUbo.update();
  26280. }
  26281. };
  26282. /** @hidden */
  26283. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26284. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26285. return;
  26286. }
  26287. this._alternateViewUpdateFlag = view.updateFlag;
  26288. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26289. this._alternateViewMatrix = view;
  26290. this._alternateProjectionMatrix = projection;
  26291. if (!this._alternateTransformMatrix) {
  26292. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26293. }
  26294. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26295. if (!this._alternateSceneUbo) {
  26296. this._createAlternateUbo();
  26297. }
  26298. if (this._alternateSceneUbo.useUbo) {
  26299. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26300. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26301. this._alternateSceneUbo.update();
  26302. }
  26303. };
  26304. /**
  26305. * Gets the uniform buffer used to store scene data
  26306. * @returns a UniformBuffer
  26307. */
  26308. Scene.prototype.getSceneUniformBuffer = function () {
  26309. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26310. };
  26311. /**
  26312. * Gets an unique (relatively to the current scene) Id
  26313. * @returns an unique number for the scene
  26314. */
  26315. Scene.prototype.getUniqueId = function () {
  26316. var result = Scene._uniqueIdCounter;
  26317. Scene._uniqueIdCounter++;
  26318. return result;
  26319. };
  26320. /**
  26321. * Add a mesh to the list of scene's meshes
  26322. * @param newMesh defines the mesh to add
  26323. * @param recursive if all child meshes should also be added to the scene
  26324. */
  26325. Scene.prototype.addMesh = function (newMesh, recursive) {
  26326. var _this = this;
  26327. if (recursive === void 0) { recursive = false; }
  26328. this.meshes.push(newMesh);
  26329. //notify the collision coordinator
  26330. if (this.collisionCoordinator) {
  26331. this.collisionCoordinator.onMeshAdded(newMesh);
  26332. }
  26333. newMesh._resyncLightSources();
  26334. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26335. if (recursive) {
  26336. newMesh.getChildMeshes().forEach(function (m) {
  26337. _this.addMesh(m);
  26338. });
  26339. }
  26340. };
  26341. /**
  26342. * Remove a mesh for the list of scene's meshes
  26343. * @param toRemove defines the mesh to remove
  26344. * @param recursive if all child meshes should also be removed from the scene
  26345. * @returns the index where the mesh was in the mesh list
  26346. */
  26347. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26348. var _this = this;
  26349. if (recursive === void 0) { recursive = false; }
  26350. var index = this.meshes.indexOf(toRemove);
  26351. if (index !== -1) {
  26352. // Remove from the scene if mesh found
  26353. this.meshes.splice(index, 1);
  26354. }
  26355. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26356. if (recursive) {
  26357. toRemove.getChildMeshes().forEach(function (m) {
  26358. _this.removeMesh(m);
  26359. });
  26360. }
  26361. return index;
  26362. };
  26363. /**
  26364. * Add a transform node to the list of scene's transform nodes
  26365. * @param newTransformNode defines the transform node to add
  26366. */
  26367. Scene.prototype.addTransformNode = function (newTransformNode) {
  26368. this.transformNodes.push(newTransformNode);
  26369. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26370. };
  26371. /**
  26372. * Remove a transform node for the list of scene's transform nodes
  26373. * @param toRemove defines the transform node to remove
  26374. * @returns the index where the transform node was in the transform node list
  26375. */
  26376. Scene.prototype.removeTransformNode = function (toRemove) {
  26377. var index = this.transformNodes.indexOf(toRemove);
  26378. if (index !== -1) {
  26379. // Remove from the scene if found
  26380. this.transformNodes.splice(index, 1);
  26381. }
  26382. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26383. return index;
  26384. };
  26385. /**
  26386. * Remove a skeleton for the list of scene's skeletons
  26387. * @param toRemove defines the skeleton to remove
  26388. * @returns the index where the skeleton was in the skeleton list
  26389. */
  26390. Scene.prototype.removeSkeleton = function (toRemove) {
  26391. var index = this.skeletons.indexOf(toRemove);
  26392. if (index !== -1) {
  26393. // Remove from the scene if found
  26394. this.skeletons.splice(index, 1);
  26395. }
  26396. return index;
  26397. };
  26398. /**
  26399. * Remove a morph target for the list of scene's morph targets
  26400. * @param toRemove defines the morph target to remove
  26401. * @returns the index where the morph target was in the morph target list
  26402. */
  26403. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26404. var index = this.morphTargetManagers.indexOf(toRemove);
  26405. if (index !== -1) {
  26406. // Remove from the scene if found
  26407. this.morphTargetManagers.splice(index, 1);
  26408. }
  26409. return index;
  26410. };
  26411. /**
  26412. * Remove a light for the list of scene's lights
  26413. * @param toRemove defines the light to remove
  26414. * @returns the index where the light was in the light list
  26415. */
  26416. Scene.prototype.removeLight = function (toRemove) {
  26417. var index = this.lights.indexOf(toRemove);
  26418. if (index !== -1) {
  26419. // Remove from meshes
  26420. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26421. var mesh = _a[_i];
  26422. mesh._removeLightSource(toRemove);
  26423. }
  26424. // Remove from the scene if mesh found
  26425. this.lights.splice(index, 1);
  26426. this.sortLightsByPriority();
  26427. }
  26428. this.onLightRemovedObservable.notifyObservers(toRemove);
  26429. return index;
  26430. };
  26431. /**
  26432. * Remove a camera for the list of scene's cameras
  26433. * @param toRemove defines the camera to remove
  26434. * @returns the index where the camera was in the camera list
  26435. */
  26436. Scene.prototype.removeCamera = function (toRemove) {
  26437. var index = this.cameras.indexOf(toRemove);
  26438. if (index !== -1) {
  26439. // Remove from the scene if mesh found
  26440. this.cameras.splice(index, 1);
  26441. }
  26442. // Remove from activeCameras
  26443. var index2 = this.activeCameras.indexOf(toRemove);
  26444. if (index2 !== -1) {
  26445. // Remove from the scene if mesh found
  26446. this.activeCameras.splice(index2, 1);
  26447. }
  26448. // Reset the activeCamera
  26449. if (this.activeCamera === toRemove) {
  26450. if (this.cameras.length > 0) {
  26451. this.activeCamera = this.cameras[0];
  26452. }
  26453. else {
  26454. this.activeCamera = null;
  26455. }
  26456. }
  26457. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26458. return index;
  26459. };
  26460. /**
  26461. * Remove a particle system for the list of scene's particle systems
  26462. * @param toRemove defines the particle system to remove
  26463. * @returns the index where the particle system was in the particle system list
  26464. */
  26465. Scene.prototype.removeParticleSystem = function (toRemove) {
  26466. var index = this.particleSystems.indexOf(toRemove);
  26467. if (index !== -1) {
  26468. this.particleSystems.splice(index, 1);
  26469. }
  26470. return index;
  26471. };
  26472. /**
  26473. * Remove a animation for the list of scene's animations
  26474. * @param toRemove defines the animation to remove
  26475. * @returns the index where the animation was in the animation list
  26476. */
  26477. Scene.prototype.removeAnimation = function (toRemove) {
  26478. var index = this.animations.indexOf(toRemove);
  26479. if (index !== -1) {
  26480. this.animations.splice(index, 1);
  26481. }
  26482. return index;
  26483. };
  26484. /**
  26485. * Removes the given animation group from this scene.
  26486. * @param toRemove The animation group to remove
  26487. * @returns The index of the removed animation group
  26488. */
  26489. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26490. var index = this.animationGroups.indexOf(toRemove);
  26491. if (index !== -1) {
  26492. this.animationGroups.splice(index, 1);
  26493. }
  26494. return index;
  26495. };
  26496. /**
  26497. * Removes the given multi-material from this scene.
  26498. * @param toRemove The multi-material to remove
  26499. * @returns The index of the removed multi-material
  26500. */
  26501. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26502. var index = this.multiMaterials.indexOf(toRemove);
  26503. if (index !== -1) {
  26504. this.multiMaterials.splice(index, 1);
  26505. }
  26506. return index;
  26507. };
  26508. /**
  26509. * Removes the given material from this scene.
  26510. * @param toRemove The material to remove
  26511. * @returns The index of the removed material
  26512. */
  26513. Scene.prototype.removeMaterial = function (toRemove) {
  26514. var index = this.materials.indexOf(toRemove);
  26515. if (index !== -1) {
  26516. this.materials.splice(index, 1);
  26517. }
  26518. return index;
  26519. };
  26520. /**
  26521. * Removes the given lens flare system from this scene.
  26522. * @param toRemove The lens flare system to remove
  26523. * @returns The index of the removed lens flare system
  26524. */
  26525. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26526. var index = this.lensFlareSystems.indexOf(toRemove);
  26527. if (index !== -1) {
  26528. this.lensFlareSystems.splice(index, 1);
  26529. }
  26530. return index;
  26531. };
  26532. /**
  26533. * Removes the given action manager from this scene.
  26534. * @param toRemove The action manager to remove
  26535. * @returns The index of the removed action manager
  26536. */
  26537. Scene.prototype.removeActionManager = function (toRemove) {
  26538. var index = this._actionManagers.indexOf(toRemove);
  26539. if (index !== -1) {
  26540. this._actionManagers.splice(index, 1);
  26541. }
  26542. return index;
  26543. };
  26544. /**
  26545. * Removes the given effect layer from this scene.
  26546. * @param toRemove defines the effect layer to remove
  26547. * @returns the index of the removed effect layer
  26548. */
  26549. Scene.prototype.removeEffectLayer = function (toRemove) {
  26550. var index = this.effectLayers.indexOf(toRemove);
  26551. if (index !== -1) {
  26552. this.effectLayers.splice(index, 1);
  26553. }
  26554. return index;
  26555. };
  26556. /**
  26557. * Removes the given texture from this scene.
  26558. * @param toRemove The texture to remove
  26559. * @returns The index of the removed texture
  26560. */
  26561. Scene.prototype.removeTexture = function (toRemove) {
  26562. var index = this.textures.indexOf(toRemove);
  26563. if (index !== -1) {
  26564. this.textures.splice(index, 1);
  26565. }
  26566. return index;
  26567. };
  26568. /**
  26569. * Adds the given light to this scene
  26570. * @param newLight The light to add
  26571. */
  26572. Scene.prototype.addLight = function (newLight) {
  26573. this.lights.push(newLight);
  26574. this.sortLightsByPriority();
  26575. // Add light to all meshes (To support if the light is removed and then readded)
  26576. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26577. var mesh = _a[_i];
  26578. if (mesh._lightSources.indexOf(newLight) === -1) {
  26579. mesh._lightSources.push(newLight);
  26580. mesh._resyncLightSources();
  26581. }
  26582. }
  26583. this.onNewLightAddedObservable.notifyObservers(newLight);
  26584. };
  26585. /**
  26586. * Sorts the list list based on light priorities
  26587. */
  26588. Scene.prototype.sortLightsByPriority = function () {
  26589. if (this.requireLightSorting) {
  26590. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26591. }
  26592. };
  26593. /**
  26594. * Adds the given camera to this scene
  26595. * @param newCamera The camera to add
  26596. */
  26597. Scene.prototype.addCamera = function (newCamera) {
  26598. this.cameras.push(newCamera);
  26599. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26600. };
  26601. /**
  26602. * Adds the given skeleton to this scene
  26603. * @param newSkeleton The skeleton to add
  26604. */
  26605. Scene.prototype.addSkeleton = function (newSkeleton) {
  26606. this.skeletons.push(newSkeleton);
  26607. };
  26608. /**
  26609. * Adds the given particle system to this scene
  26610. * @param newParticleSystem The particle system to add
  26611. */
  26612. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26613. this.particleSystems.push(newParticleSystem);
  26614. };
  26615. /**
  26616. * Adds the given animation to this scene
  26617. * @param newAnimation The animation to add
  26618. */
  26619. Scene.prototype.addAnimation = function (newAnimation) {
  26620. this.animations.push(newAnimation);
  26621. };
  26622. /**
  26623. * Adds the given animation group to this scene.
  26624. * @param newAnimationGroup The animation group to add
  26625. */
  26626. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26627. this.animationGroups.push(newAnimationGroup);
  26628. };
  26629. /**
  26630. * Adds the given multi-material to this scene
  26631. * @param newMultiMaterial The multi-material to add
  26632. */
  26633. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26634. this.multiMaterials.push(newMultiMaterial);
  26635. };
  26636. /**
  26637. * Adds the given material to this scene
  26638. * @param newMaterial The material to add
  26639. */
  26640. Scene.prototype.addMaterial = function (newMaterial) {
  26641. this.materials.push(newMaterial);
  26642. };
  26643. /**
  26644. * Adds the given morph target to this scene
  26645. * @param newMorphTargetManager The morph target to add
  26646. */
  26647. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26648. this.morphTargetManagers.push(newMorphTargetManager);
  26649. };
  26650. /**
  26651. * Adds the given geometry to this scene
  26652. * @param newGeometry The geometry to add
  26653. */
  26654. Scene.prototype.addGeometry = function (newGeometry) {
  26655. this._geometries.push(newGeometry);
  26656. };
  26657. /**
  26658. * Adds the given lens flare system to this scene
  26659. * @param newLensFlareSystem The lens flare system to add
  26660. */
  26661. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26662. this.lensFlareSystems.push(newLensFlareSystem);
  26663. };
  26664. /**
  26665. * Adds the given effect layer to this scene
  26666. * @param newEffectLayer defines the effect layer to add
  26667. */
  26668. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26669. this.effectLayers.push(newEffectLayer);
  26670. };
  26671. /**
  26672. * Adds the given action manager to this scene
  26673. * @param newActionManager The action manager to add
  26674. */
  26675. Scene.prototype.addActionManager = function (newActionManager) {
  26676. this._actionManagers.push(newActionManager);
  26677. };
  26678. /**
  26679. * Adds the given texture to this scene.
  26680. * @param newTexture The texture to add
  26681. */
  26682. Scene.prototype.addTexture = function (newTexture) {
  26683. this.textures.push(newTexture);
  26684. };
  26685. /**
  26686. * Switch active camera
  26687. * @param newCamera defines the new active camera
  26688. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26689. */
  26690. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26691. if (attachControl === void 0) { attachControl = true; }
  26692. var canvas = this._engine.getRenderingCanvas();
  26693. if (!canvas) {
  26694. return;
  26695. }
  26696. if (this.activeCamera) {
  26697. this.activeCamera.detachControl(canvas);
  26698. }
  26699. this.activeCamera = newCamera;
  26700. if (attachControl) {
  26701. newCamera.attachControl(canvas);
  26702. }
  26703. };
  26704. /**
  26705. * sets the active camera of the scene using its ID
  26706. * @param id defines the camera's ID
  26707. * @return the new active camera or null if none found.
  26708. */
  26709. Scene.prototype.setActiveCameraByID = function (id) {
  26710. var camera = this.getCameraByID(id);
  26711. if (camera) {
  26712. this.activeCamera = camera;
  26713. return camera;
  26714. }
  26715. return null;
  26716. };
  26717. /**
  26718. * sets the active camera of the scene using its name
  26719. * @param name defines the camera's name
  26720. * @returns the new active camera or null if none found.
  26721. */
  26722. Scene.prototype.setActiveCameraByName = function (name) {
  26723. var camera = this.getCameraByName(name);
  26724. if (camera) {
  26725. this.activeCamera = camera;
  26726. return camera;
  26727. }
  26728. return null;
  26729. };
  26730. /**
  26731. * get an animation group using its name
  26732. * @param name defines the material's name
  26733. * @return the animation group or null if none found.
  26734. */
  26735. Scene.prototype.getAnimationGroupByName = function (name) {
  26736. for (var index = 0; index < this.animationGroups.length; index++) {
  26737. if (this.animationGroups[index].name === name) {
  26738. return this.animationGroups[index];
  26739. }
  26740. }
  26741. return null;
  26742. };
  26743. /**
  26744. * get a material using its id
  26745. * @param id defines the material's ID
  26746. * @return the material or null if none found.
  26747. */
  26748. Scene.prototype.getMaterialByID = function (id) {
  26749. for (var index = 0; index < this.materials.length; index++) {
  26750. if (this.materials[index].id === id) {
  26751. return this.materials[index];
  26752. }
  26753. }
  26754. return null;
  26755. };
  26756. /**
  26757. * Gets a material using its name
  26758. * @param name defines the material's name
  26759. * @return the material or null if none found.
  26760. */
  26761. Scene.prototype.getMaterialByName = function (name) {
  26762. for (var index = 0; index < this.materials.length; index++) {
  26763. if (this.materials[index].name === name) {
  26764. return this.materials[index];
  26765. }
  26766. }
  26767. return null;
  26768. };
  26769. /**
  26770. * Gets a lens flare system using its name
  26771. * @param name defines the name to look for
  26772. * @returns the lens flare system or null if not found
  26773. */
  26774. Scene.prototype.getLensFlareSystemByName = function (name) {
  26775. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26776. if (this.lensFlareSystems[index].name === name) {
  26777. return this.lensFlareSystems[index];
  26778. }
  26779. }
  26780. return null;
  26781. };
  26782. /**
  26783. * Gets a lens flare system using its id
  26784. * @param id defines the id to look for
  26785. * @returns the lens flare system or null if not found
  26786. */
  26787. Scene.prototype.getLensFlareSystemByID = function (id) {
  26788. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26789. if (this.lensFlareSystems[index].id === id) {
  26790. return this.lensFlareSystems[index];
  26791. }
  26792. }
  26793. return null;
  26794. };
  26795. /**
  26796. * Gets a camera using its id
  26797. * @param id defines the id to look for
  26798. * @returns the camera or null if not found
  26799. */
  26800. Scene.prototype.getCameraByID = function (id) {
  26801. for (var index = 0; index < this.cameras.length; index++) {
  26802. if (this.cameras[index].id === id) {
  26803. return this.cameras[index];
  26804. }
  26805. }
  26806. return null;
  26807. };
  26808. /**
  26809. * Gets a camera using its unique id
  26810. * @param uniqueId defines the unique id to look for
  26811. * @returns the camera or null if not found
  26812. */
  26813. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26814. for (var index = 0; index < this.cameras.length; index++) {
  26815. if (this.cameras[index].uniqueId === uniqueId) {
  26816. return this.cameras[index];
  26817. }
  26818. }
  26819. return null;
  26820. };
  26821. /**
  26822. * Gets a camera using its name
  26823. * @param name defines the camera's name
  26824. * @return the camera or null if none found.
  26825. */
  26826. Scene.prototype.getCameraByName = function (name) {
  26827. for (var index = 0; index < this.cameras.length; index++) {
  26828. if (this.cameras[index].name === name) {
  26829. return this.cameras[index];
  26830. }
  26831. }
  26832. return null;
  26833. };
  26834. /**
  26835. * Gets a bone using its id
  26836. * @param id defines the bone's id
  26837. * @return the bone or null if not found
  26838. */
  26839. Scene.prototype.getBoneByID = function (id) {
  26840. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26841. var skeleton = this.skeletons[skeletonIndex];
  26842. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26843. if (skeleton.bones[boneIndex].id === id) {
  26844. return skeleton.bones[boneIndex];
  26845. }
  26846. }
  26847. }
  26848. return null;
  26849. };
  26850. /**
  26851. * Gets a bone using its id
  26852. * @param name defines the bone's name
  26853. * @return the bone or null if not found
  26854. */
  26855. Scene.prototype.getBoneByName = function (name) {
  26856. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26857. var skeleton = this.skeletons[skeletonIndex];
  26858. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26859. if (skeleton.bones[boneIndex].name === name) {
  26860. return skeleton.bones[boneIndex];
  26861. }
  26862. }
  26863. }
  26864. return null;
  26865. };
  26866. /**
  26867. * Gets a light node using its name
  26868. * @param name defines the the light's name
  26869. * @return the light or null if none found.
  26870. */
  26871. Scene.prototype.getLightByName = function (name) {
  26872. for (var index = 0; index < this.lights.length; index++) {
  26873. if (this.lights[index].name === name) {
  26874. return this.lights[index];
  26875. }
  26876. }
  26877. return null;
  26878. };
  26879. /**
  26880. * Gets a light node using its id
  26881. * @param id defines the light's id
  26882. * @return the light or null if none found.
  26883. */
  26884. Scene.prototype.getLightByID = function (id) {
  26885. for (var index = 0; index < this.lights.length; index++) {
  26886. if (this.lights[index].id === id) {
  26887. return this.lights[index];
  26888. }
  26889. }
  26890. return null;
  26891. };
  26892. /**
  26893. * Gets a light node using its scene-generated unique ID
  26894. * @param uniqueId defines the light's unique id
  26895. * @return the light or null if none found.
  26896. */
  26897. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26898. for (var index = 0; index < this.lights.length; index++) {
  26899. if (this.lights[index].uniqueId === uniqueId) {
  26900. return this.lights[index];
  26901. }
  26902. }
  26903. return null;
  26904. };
  26905. /**
  26906. * Gets a particle system by id
  26907. * @param id defines the particle system id
  26908. * @return the corresponding system or null if none found
  26909. */
  26910. Scene.prototype.getParticleSystemByID = function (id) {
  26911. for (var index = 0; index < this.particleSystems.length; index++) {
  26912. if (this.particleSystems[index].id === id) {
  26913. return this.particleSystems[index];
  26914. }
  26915. }
  26916. return null;
  26917. };
  26918. /**
  26919. * Gets a geometry using its ID
  26920. * @param id defines the geometry's id
  26921. * @return the geometry or null if none found.
  26922. */
  26923. Scene.prototype.getGeometryByID = function (id) {
  26924. for (var index = 0; index < this._geometries.length; index++) {
  26925. if (this._geometries[index].id === id) {
  26926. return this._geometries[index];
  26927. }
  26928. }
  26929. return null;
  26930. };
  26931. /**
  26932. * Add a new geometry to this scene
  26933. * @param geometry defines the geometry to be added to the scene.
  26934. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26935. * @return a boolean defining if the geometry was added or not
  26936. */
  26937. Scene.prototype.pushGeometry = function (geometry, force) {
  26938. if (!force && this.getGeometryByID(geometry.id)) {
  26939. return false;
  26940. }
  26941. this._geometries.push(geometry);
  26942. //notify the collision coordinator
  26943. if (this.collisionCoordinator) {
  26944. this.collisionCoordinator.onGeometryAdded(geometry);
  26945. }
  26946. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26947. return true;
  26948. };
  26949. /**
  26950. * Removes an existing geometry
  26951. * @param geometry defines the geometry to be removed from the scene
  26952. * @return a boolean defining if the geometry was removed or not
  26953. */
  26954. Scene.prototype.removeGeometry = function (geometry) {
  26955. var index = this._geometries.indexOf(geometry);
  26956. if (index > -1) {
  26957. this._geometries.splice(index, 1);
  26958. //notify the collision coordinator
  26959. if (this.collisionCoordinator) {
  26960. this.collisionCoordinator.onGeometryDeleted(geometry);
  26961. }
  26962. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26963. return true;
  26964. }
  26965. return false;
  26966. };
  26967. /**
  26968. * Gets the list of geometries attached to the scene
  26969. * @returns an array of Geometry
  26970. */
  26971. Scene.prototype.getGeometries = function () {
  26972. return this._geometries;
  26973. };
  26974. /**
  26975. * Gets the first added mesh found of a given ID
  26976. * @param id defines the id to search for
  26977. * @return the mesh found or null if not found at all
  26978. */
  26979. Scene.prototype.getMeshByID = function (id) {
  26980. for (var index = 0; index < this.meshes.length; index++) {
  26981. if (this.meshes[index].id === id) {
  26982. return this.meshes[index];
  26983. }
  26984. }
  26985. return null;
  26986. };
  26987. /**
  26988. * Gets a list of meshes using their id
  26989. * @param id defines the id to search for
  26990. * @returns a list of meshes
  26991. */
  26992. Scene.prototype.getMeshesByID = function (id) {
  26993. return this.meshes.filter(function (m) {
  26994. return m.id === id;
  26995. });
  26996. };
  26997. /**
  26998. * Gets the first added transform node found of a given ID
  26999. * @param id defines the id to search for
  27000. * @return the found transform node or null if not found at all.
  27001. */
  27002. Scene.prototype.getTransformNodeByID = function (id) {
  27003. for (var index = 0; index < this.transformNodes.length; index++) {
  27004. if (this.transformNodes[index].id === id) {
  27005. return this.transformNodes[index];
  27006. }
  27007. }
  27008. return null;
  27009. };
  27010. /**
  27011. * Gets a list of transform nodes using their id
  27012. * @param id defines the id to search for
  27013. * @returns a list of transform nodes
  27014. */
  27015. Scene.prototype.getTransformNodesByID = function (id) {
  27016. return this.transformNodes.filter(function (m) {
  27017. return m.id === id;
  27018. });
  27019. };
  27020. /**
  27021. * Gets a mesh with its auto-generated unique id
  27022. * @param uniqueId defines the unique id to search for
  27023. * @return the found mesh or null if not found at all.
  27024. */
  27025. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27026. for (var index = 0; index < this.meshes.length; index++) {
  27027. if (this.meshes[index].uniqueId === uniqueId) {
  27028. return this.meshes[index];
  27029. }
  27030. }
  27031. return null;
  27032. };
  27033. /**
  27034. * Gets a the last added mesh using a given id
  27035. * @param id defines the id to search for
  27036. * @return the found mesh or null if not found at all.
  27037. */
  27038. Scene.prototype.getLastMeshByID = function (id) {
  27039. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27040. if (this.meshes[index].id === id) {
  27041. return this.meshes[index];
  27042. }
  27043. }
  27044. return null;
  27045. };
  27046. /**
  27047. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27048. * @param id defines the id to search for
  27049. * @return the found node or null if not found at all
  27050. */
  27051. Scene.prototype.getLastEntryByID = function (id) {
  27052. var index;
  27053. for (index = this.meshes.length - 1; index >= 0; index--) {
  27054. if (this.meshes[index].id === id) {
  27055. return this.meshes[index];
  27056. }
  27057. }
  27058. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27059. if (this.transformNodes[index].id === id) {
  27060. return this.transformNodes[index];
  27061. }
  27062. }
  27063. for (index = this.cameras.length - 1; index >= 0; index--) {
  27064. if (this.cameras[index].id === id) {
  27065. return this.cameras[index];
  27066. }
  27067. }
  27068. for (index = this.lights.length - 1; index >= 0; index--) {
  27069. if (this.lights[index].id === id) {
  27070. return this.lights[index];
  27071. }
  27072. }
  27073. return null;
  27074. };
  27075. /**
  27076. * Gets a node (Mesh, Camera, Light) using a given id
  27077. * @param id defines the id to search for
  27078. * @return the found node or null if not found at all
  27079. */
  27080. Scene.prototype.getNodeByID = function (id) {
  27081. var mesh = this.getMeshByID(id);
  27082. if (mesh) {
  27083. return mesh;
  27084. }
  27085. var light = this.getLightByID(id);
  27086. if (light) {
  27087. return light;
  27088. }
  27089. var camera = this.getCameraByID(id);
  27090. if (camera) {
  27091. return camera;
  27092. }
  27093. var bone = this.getBoneByID(id);
  27094. return bone;
  27095. };
  27096. /**
  27097. * Gets a node (Mesh, Camera, Light) using a given name
  27098. * @param name defines the name to search for
  27099. * @return the found node or null if not found at all.
  27100. */
  27101. Scene.prototype.getNodeByName = function (name) {
  27102. var mesh = this.getMeshByName(name);
  27103. if (mesh) {
  27104. return mesh;
  27105. }
  27106. var light = this.getLightByName(name);
  27107. if (light) {
  27108. return light;
  27109. }
  27110. var camera = this.getCameraByName(name);
  27111. if (camera) {
  27112. return camera;
  27113. }
  27114. var bone = this.getBoneByName(name);
  27115. return bone;
  27116. };
  27117. /**
  27118. * Gets a mesh using a given name
  27119. * @param name defines the name to search for
  27120. * @return the found mesh or null if not found at all.
  27121. */
  27122. Scene.prototype.getMeshByName = function (name) {
  27123. for (var index = 0; index < this.meshes.length; index++) {
  27124. if (this.meshes[index].name === name) {
  27125. return this.meshes[index];
  27126. }
  27127. }
  27128. return null;
  27129. };
  27130. /**
  27131. * Gets a transform node using a given name
  27132. * @param name defines the name to search for
  27133. * @return the found transform node or null if not found at all.
  27134. */
  27135. Scene.prototype.getTransformNodeByName = function (name) {
  27136. for (var index = 0; index < this.transformNodes.length; index++) {
  27137. if (this.transformNodes[index].name === name) {
  27138. return this.transformNodes[index];
  27139. }
  27140. }
  27141. return null;
  27142. };
  27143. /**
  27144. * Gets a sound using a given name
  27145. * @param name defines the name to search for
  27146. * @return the found sound or null if not found at all.
  27147. */
  27148. Scene.prototype.getSoundByName = function (name) {
  27149. var index;
  27150. if (BABYLON.AudioEngine) {
  27151. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27152. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27153. return this.mainSoundTrack.soundCollection[index];
  27154. }
  27155. }
  27156. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27157. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27158. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27159. return this.soundTracks[sdIndex].soundCollection[index];
  27160. }
  27161. }
  27162. }
  27163. }
  27164. return null;
  27165. };
  27166. /**
  27167. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27168. * @param id defines the id to search for
  27169. * @return the found skeleton or null if not found at all.
  27170. */
  27171. Scene.prototype.getLastSkeletonByID = function (id) {
  27172. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27173. if (this.skeletons[index].id === id) {
  27174. return this.skeletons[index];
  27175. }
  27176. }
  27177. return null;
  27178. };
  27179. /**
  27180. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27181. * @param id defines the id to search for
  27182. * @return the found skeleton or null if not found at all.
  27183. */
  27184. Scene.prototype.getSkeletonById = function (id) {
  27185. for (var index = 0; index < this.skeletons.length; index++) {
  27186. if (this.skeletons[index].id === id) {
  27187. return this.skeletons[index];
  27188. }
  27189. }
  27190. return null;
  27191. };
  27192. /**
  27193. * Gets a skeleton using a given name
  27194. * @param name defines the name to search for
  27195. * @return the found skeleton or null if not found at all.
  27196. */
  27197. Scene.prototype.getSkeletonByName = function (name) {
  27198. for (var index = 0; index < this.skeletons.length; index++) {
  27199. if (this.skeletons[index].name === name) {
  27200. return this.skeletons[index];
  27201. }
  27202. }
  27203. return null;
  27204. };
  27205. /**
  27206. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27207. * @param id defines the id to search for
  27208. * @return the found morph target manager or null if not found at all.
  27209. */
  27210. Scene.prototype.getMorphTargetManagerById = function (id) {
  27211. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27212. if (this.morphTargetManagers[index].uniqueId === id) {
  27213. return this.morphTargetManagers[index];
  27214. }
  27215. }
  27216. return null;
  27217. };
  27218. /**
  27219. * Gets a boolean indicating if the given mesh is active
  27220. * @param mesh defines the mesh to look for
  27221. * @returns true if the mesh is in the active list
  27222. */
  27223. Scene.prototype.isActiveMesh = function (mesh) {
  27224. return (this._activeMeshes.indexOf(mesh) !== -1);
  27225. };
  27226. /**
  27227. * Return a the first highlight layer of the scene with a given name.
  27228. * @param name The name of the highlight layer to look for.
  27229. * @return The highlight layer if found otherwise null.
  27230. */
  27231. Scene.prototype.getHighlightLayerByName = function (name) {
  27232. for (var index = 0; index < this.effectLayers.length; index++) {
  27233. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27234. return this.effectLayers[index];
  27235. }
  27236. }
  27237. return null;
  27238. };
  27239. /**
  27240. * Return a the first highlight layer of the scene with a given name.
  27241. * @param name The name of the highlight layer to look for.
  27242. * @return The highlight layer if found otherwise null.
  27243. */
  27244. Scene.prototype.getGlowLayerByName = function (name) {
  27245. for (var index = 0; index < this.effectLayers.length; index++) {
  27246. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27247. return this.effectLayers[index];
  27248. }
  27249. }
  27250. return null;
  27251. };
  27252. Object.defineProperty(Scene.prototype, "uid", {
  27253. /**
  27254. * Return a unique id as a string which can serve as an identifier for the scene
  27255. */
  27256. get: function () {
  27257. if (!this._uid) {
  27258. this._uid = BABYLON.Tools.RandomId();
  27259. }
  27260. return this._uid;
  27261. },
  27262. enumerable: true,
  27263. configurable: true
  27264. });
  27265. /**
  27266. * Add an externaly attached data from its key.
  27267. * This method call will fail and return false, if such key already exists.
  27268. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27269. * @param key the unique key that identifies the data
  27270. * @param data the data object to associate to the key for this Engine instance
  27271. * @return true if no such key were already present and the data was added successfully, false otherwise
  27272. */
  27273. Scene.prototype.addExternalData = function (key, data) {
  27274. if (!this._externalData) {
  27275. this._externalData = new BABYLON.StringDictionary();
  27276. }
  27277. return this._externalData.add(key, data);
  27278. };
  27279. /**
  27280. * Get an externaly attached data from its key
  27281. * @param key the unique key that identifies the data
  27282. * @return the associated data, if present (can be null), or undefined if not present
  27283. */
  27284. Scene.prototype.getExternalData = function (key) {
  27285. if (!this._externalData) {
  27286. return null;
  27287. }
  27288. return this._externalData.get(key);
  27289. };
  27290. /**
  27291. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27292. * @param key the unique key that identifies the data
  27293. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27294. * @return the associated data, can be null if the factory returned null.
  27295. */
  27296. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27297. if (!this._externalData) {
  27298. this._externalData = new BABYLON.StringDictionary();
  27299. }
  27300. return this._externalData.getOrAddWithFactory(key, factory);
  27301. };
  27302. /**
  27303. * Remove an externaly attached data from the Engine instance
  27304. * @param key the unique key that identifies the data
  27305. * @return true if the data was successfully removed, false if it doesn't exist
  27306. */
  27307. Scene.prototype.removeExternalData = function (key) {
  27308. return this._externalData.remove(key);
  27309. };
  27310. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27311. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27312. if (mesh.showSubMeshesBoundingBox) {
  27313. var boundingInfo = subMesh.getBoundingInfo();
  27314. if (boundingInfo !== null && boundingInfo !== undefined) {
  27315. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27316. }
  27317. }
  27318. var material = subMesh.getMaterial();
  27319. if (material !== null && material !== undefined) {
  27320. // Render targets
  27321. if (material.getRenderTargetTextures !== undefined) {
  27322. if (this._processedMaterials.indexOf(material) === -1) {
  27323. this._processedMaterials.push(material);
  27324. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27325. }
  27326. }
  27327. // Dispatch
  27328. this._activeIndices.addCount(subMesh.indexCount, false);
  27329. this._renderingManager.dispatch(subMesh, mesh, material);
  27330. }
  27331. }
  27332. };
  27333. /**
  27334. * Clear the processed materials smart array preventing retention point in material dispose.
  27335. */
  27336. Scene.prototype.freeProcessedMaterials = function () {
  27337. this._processedMaterials.dispose();
  27338. };
  27339. /**
  27340. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27341. */
  27342. Scene.prototype.freeActiveMeshes = function () {
  27343. this._activeMeshes.dispose();
  27344. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27345. this.activeCamera._activeMeshes.dispose();
  27346. }
  27347. if (this.activeCameras) {
  27348. for (var i = 0; i < this.activeCameras.length; i++) {
  27349. var activeCamera = this.activeCameras[i];
  27350. if (activeCamera && activeCamera._activeMeshes) {
  27351. activeCamera._activeMeshes.dispose();
  27352. }
  27353. }
  27354. }
  27355. };
  27356. /**
  27357. * Clear the info related to rendering groups preventing retention points during dispose.
  27358. */
  27359. Scene.prototype.freeRenderingGroups = function () {
  27360. if (this._renderingManager) {
  27361. this._renderingManager.freeRenderingGroups();
  27362. }
  27363. if (this.textures) {
  27364. for (var i = 0; i < this.textures.length; i++) {
  27365. var texture = this.textures[i];
  27366. if (texture && texture.renderList) {
  27367. texture.freeRenderingGroups();
  27368. }
  27369. }
  27370. }
  27371. };
  27372. /** @hidden */
  27373. Scene.prototype._isInIntermediateRendering = function () {
  27374. return this._intermediateRendering;
  27375. };
  27376. /**
  27377. * Defines the current active mesh candidate provider
  27378. * @param provider defines the provider to use
  27379. */
  27380. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27381. this._activeMeshCandidateProvider = provider;
  27382. };
  27383. /**
  27384. * Gets the current active mesh candidate provider
  27385. * @returns the current active mesh candidate provider
  27386. */
  27387. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27388. return this._activeMeshCandidateProvider;
  27389. };
  27390. /**
  27391. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27392. * @returns the current scene
  27393. */
  27394. Scene.prototype.freezeActiveMeshes = function () {
  27395. if (!this.activeCamera) {
  27396. return this;
  27397. }
  27398. if (!this._frustumPlanes) {
  27399. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27400. }
  27401. this._evaluateActiveMeshes();
  27402. this._activeMeshesFrozen = true;
  27403. return this;
  27404. };
  27405. /**
  27406. * Use this function to restart evaluating active meshes on every frame
  27407. * @returns the current scene
  27408. */
  27409. Scene.prototype.unfreezeActiveMeshes = function () {
  27410. this._activeMeshesFrozen = false;
  27411. return this;
  27412. };
  27413. Scene.prototype._evaluateActiveMeshes = function () {
  27414. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27415. return;
  27416. }
  27417. if (!this.activeCamera) {
  27418. return;
  27419. }
  27420. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27421. this.activeCamera._activeMeshes.reset();
  27422. this._activeMeshes.reset();
  27423. this._renderingManager.reset();
  27424. this._processedMaterials.reset();
  27425. this._activeParticleSystems.reset();
  27426. this._activeSkeletons.reset();
  27427. this._softwareSkinnedMeshes.reset();
  27428. if (this._boundingBoxRenderer) {
  27429. this._boundingBoxRenderer.reset();
  27430. }
  27431. // Meshes
  27432. var meshes;
  27433. var len;
  27434. var checkIsEnabled = true;
  27435. // Determine mesh candidates
  27436. if (this._activeMeshCandidateProvider !== undefined) {
  27437. // Use _activeMeshCandidateProvider
  27438. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27439. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27440. if (meshes !== undefined) {
  27441. len = meshes.length;
  27442. }
  27443. else {
  27444. len = 0;
  27445. }
  27446. }
  27447. else if (this._selectionOctree !== undefined) {
  27448. // Octree
  27449. var selection = this._selectionOctree.select(this._frustumPlanes);
  27450. meshes = selection.data;
  27451. len = selection.length;
  27452. }
  27453. else {
  27454. // Full scene traversal
  27455. len = this.meshes.length;
  27456. meshes = this.meshes;
  27457. }
  27458. // Check each mesh
  27459. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27460. mesh = meshes[meshIndex];
  27461. if (mesh.isBlocked) {
  27462. continue;
  27463. }
  27464. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27465. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27466. continue;
  27467. }
  27468. mesh.computeWorldMatrix();
  27469. // Intersections
  27470. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27471. this._meshesForIntersections.pushNoDuplicate(mesh);
  27472. }
  27473. // Switch to current LOD
  27474. meshLOD = mesh.getLOD(this.activeCamera);
  27475. if (meshLOD === undefined || meshLOD === null) {
  27476. continue;
  27477. }
  27478. mesh._preActivate();
  27479. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27480. this._activeMeshes.push(mesh);
  27481. this.activeCamera._activeMeshes.push(mesh);
  27482. mesh._activate(this._renderId);
  27483. if (meshLOD !== mesh) {
  27484. meshLOD._activate(this._renderId);
  27485. }
  27486. this._activeMesh(mesh, meshLOD);
  27487. }
  27488. }
  27489. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27490. // Particle systems
  27491. if (this.particlesEnabled) {
  27492. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27493. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27494. var particleSystem = this.particleSystems[particleIndex];
  27495. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27496. continue;
  27497. }
  27498. var emitter = particleSystem.emitter;
  27499. if (!emitter.position || emitter.isEnabled()) {
  27500. this._activeParticleSystems.push(particleSystem);
  27501. particleSystem.animate();
  27502. this._renderingManager.dispatchParticles(particleSystem);
  27503. }
  27504. }
  27505. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27506. }
  27507. };
  27508. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27509. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27510. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27511. mesh.skeleton.prepare();
  27512. }
  27513. if (!mesh.computeBonesUsingShaders) {
  27514. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27515. }
  27516. }
  27517. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27518. var boundingInfo = sourceMesh.getBoundingInfo();
  27519. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27520. }
  27521. if (mesh !== undefined && mesh !== null
  27522. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27523. // Submeshes Octrees
  27524. var len;
  27525. var subMeshes;
  27526. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27527. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27528. len = intersections.length;
  27529. subMeshes = intersections.data;
  27530. }
  27531. else {
  27532. subMeshes = mesh.subMeshes;
  27533. len = subMeshes.length;
  27534. }
  27535. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27536. subMesh = subMeshes[subIndex];
  27537. this._evaluateSubMesh(subMesh, mesh);
  27538. }
  27539. }
  27540. };
  27541. /**
  27542. * Update the transform matrix to update from the current active camera
  27543. * @param force defines a boolean used to force the update even if cache is up to date
  27544. */
  27545. Scene.prototype.updateTransformMatrix = function (force) {
  27546. if (!this.activeCamera) {
  27547. return;
  27548. }
  27549. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27550. };
  27551. /**
  27552. * 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)
  27553. * @param alternateCamera defines the camera to use
  27554. */
  27555. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27556. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27557. };
  27558. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27559. if (camera && camera._skipRendering) {
  27560. return;
  27561. }
  27562. var engine = this._engine;
  27563. this.activeCamera = camera;
  27564. if (!this.activeCamera)
  27565. throw new Error("Active camera not set");
  27566. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27567. // Viewport
  27568. engine.setViewport(this.activeCamera.viewport);
  27569. // Camera
  27570. this.resetCachedMaterial();
  27571. this._renderId++;
  27572. this.updateTransformMatrix();
  27573. if (camera._alternateCamera) {
  27574. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27575. this._alternateRendering = true;
  27576. }
  27577. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27578. // Meshes
  27579. this._evaluateActiveMeshes();
  27580. // Software skinning
  27581. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27582. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27583. mesh.applySkeleton(mesh.skeleton);
  27584. }
  27585. // Render targets
  27586. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27587. var needsRestoreFrameBuffer = false;
  27588. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27589. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27590. }
  27591. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27592. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27593. }
  27594. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27595. this._intermediateRendering = true;
  27596. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27597. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27598. var renderTarget = this._renderTargets.data[renderIndex];
  27599. if (renderTarget._shouldRender()) {
  27600. this._renderId++;
  27601. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27602. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27603. }
  27604. }
  27605. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27606. this._intermediateRendering = false;
  27607. this._renderId++;
  27608. needsRestoreFrameBuffer = true; // Restore back buffer
  27609. }
  27610. // Render EffecttLayer Texture
  27611. var stencilState = this._engine.getStencilBuffer();
  27612. var renderEffects = false;
  27613. var needStencil = false;
  27614. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27615. this._intermediateRendering = true;
  27616. for (var i = 0; i < this.effectLayers.length; i++) {
  27617. var effectLayer = this.effectLayers[i];
  27618. if (effectLayer.shouldRender() &&
  27619. (!effectLayer.camera ||
  27620. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27621. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27622. renderEffects = true;
  27623. needStencil = needStencil || effectLayer.needStencil();
  27624. var renderTarget = effectLayer._mainTexture;
  27625. if (renderTarget._shouldRender()) {
  27626. this._renderId++;
  27627. renderTarget.render(false, false);
  27628. needsRestoreFrameBuffer = true;
  27629. }
  27630. }
  27631. }
  27632. this._intermediateRendering = false;
  27633. this._renderId++;
  27634. }
  27635. if (needsRestoreFrameBuffer) {
  27636. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27637. }
  27638. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27639. // Prepare Frame
  27640. this.postProcessManager._prepareFrame();
  27641. // Backgrounds
  27642. var layerIndex;
  27643. var layer;
  27644. if (this.layers.length) {
  27645. engine.setDepthBuffer(false);
  27646. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27647. layer = this.layers[layerIndex];
  27648. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27649. layer.render();
  27650. }
  27651. }
  27652. engine.setDepthBuffer(true);
  27653. }
  27654. // Activate effect Layer stencil
  27655. if (needStencil) {
  27656. this._engine.setStencilBuffer(true);
  27657. }
  27658. // Render
  27659. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27660. this._renderingManager.render(null, null, true, true);
  27661. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27662. // Restore effect Layer stencil
  27663. if (needStencil) {
  27664. this._engine.setStencilBuffer(stencilState);
  27665. }
  27666. // Bounding boxes
  27667. if (this._boundingBoxRenderer) {
  27668. this._boundingBoxRenderer.render();
  27669. }
  27670. // Lens flares
  27671. if (this.lensFlaresEnabled) {
  27672. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27673. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27674. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27675. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27676. lensFlareSystem.render();
  27677. }
  27678. }
  27679. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27680. }
  27681. // Effect Layer
  27682. if (renderEffects) {
  27683. engine.setDepthBuffer(false);
  27684. for (var i = 0; i < this.effectLayers.length; i++) {
  27685. if (this.effectLayers[i].shouldRender()) {
  27686. this.effectLayers[i].render();
  27687. }
  27688. }
  27689. engine.setDepthBuffer(true);
  27690. }
  27691. // Foregrounds
  27692. if (this.layers.length) {
  27693. engine.setDepthBuffer(false);
  27694. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27695. layer = this.layers[layerIndex];
  27696. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27697. layer.render();
  27698. }
  27699. }
  27700. engine.setDepthBuffer(true);
  27701. }
  27702. // Finalize frame
  27703. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27704. // Reset some special arrays
  27705. this._renderTargets.reset();
  27706. this._alternateRendering = false;
  27707. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27708. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27709. };
  27710. Scene.prototype._processSubCameras = function (camera) {
  27711. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27712. this._renderForCamera(camera);
  27713. return;
  27714. }
  27715. // rig cameras
  27716. for (var index = 0; index < camera._rigCameras.length; index++) {
  27717. this._renderForCamera(camera._rigCameras[index], camera);
  27718. }
  27719. this.activeCamera = camera;
  27720. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27721. };
  27722. Scene.prototype._checkIntersections = function () {
  27723. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27724. var sourceMesh = this._meshesForIntersections.data[index];
  27725. if (!sourceMesh.actionManager) {
  27726. continue;
  27727. }
  27728. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27729. var action = sourceMesh.actionManager.actions[actionIndex];
  27730. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27731. var parameters = action.getTriggerParameter();
  27732. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27733. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27734. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27735. if (areIntersecting && currentIntersectionInProgress === -1) {
  27736. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27737. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27738. sourceMesh._intersectionsInProgress.push(otherMesh);
  27739. }
  27740. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27741. sourceMesh._intersectionsInProgress.push(otherMesh);
  27742. }
  27743. }
  27744. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27745. //They intersected, and now they don't.
  27746. //is this trigger an exit trigger? execute an event.
  27747. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27748. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27749. }
  27750. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27751. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27752. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27753. return otherMesh === parameterMesh;
  27754. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27755. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27756. }
  27757. }
  27758. }
  27759. }
  27760. }
  27761. };
  27762. /**
  27763. * Render the scene
  27764. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27765. */
  27766. Scene.prototype.render = function (updateCameras) {
  27767. if (updateCameras === void 0) { updateCameras = true; }
  27768. if (this.isDisposed) {
  27769. return;
  27770. }
  27771. this._activeParticles.fetchNewFrame();
  27772. this._totalVertices.fetchNewFrame();
  27773. this._activeIndices.fetchNewFrame();
  27774. this._activeBones.fetchNewFrame();
  27775. this._meshesForIntersections.reset();
  27776. this.resetCachedMaterial();
  27777. this.onBeforeAnimationsObservable.notifyObservers(this);
  27778. // Actions
  27779. if (this.actionManager) {
  27780. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27781. }
  27782. //Simplification Queue
  27783. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27784. this.simplificationQueue.executeNext();
  27785. }
  27786. if (this._engine.isDeterministicLockStep()) {
  27787. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27788. var defaultFPS = (60.0 / 1000.0);
  27789. var defaultFrameTime = 1000 / 60; // frame time in MS
  27790. if (this._physicsEngine) {
  27791. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27792. }
  27793. var stepsTaken = 0;
  27794. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27795. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27796. internalSteps = Math.min(internalSteps, maxSubSteps);
  27797. do {
  27798. this.onBeforeStepObservable.notifyObservers(this);
  27799. // Animations
  27800. this._animationRatio = defaultFrameTime * defaultFPS;
  27801. this._animate();
  27802. this.onAfterAnimationsObservable.notifyObservers(this);
  27803. // Physics
  27804. if (this._physicsEngine) {
  27805. this.onBeforePhysicsObservable.notifyObservers(this);
  27806. this._physicsEngine._step(defaultFrameTime / 1000);
  27807. this.onAfterPhysicsObservable.notifyObservers(this);
  27808. }
  27809. this.onAfterStepObservable.notifyObservers(this);
  27810. this._currentStepId++;
  27811. stepsTaken++;
  27812. deltaTime -= defaultFrameTime;
  27813. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27814. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27815. }
  27816. else {
  27817. // Animations
  27818. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27819. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27820. this._animate();
  27821. this.onAfterAnimationsObservable.notifyObservers(this);
  27822. // Physics
  27823. if (this._physicsEngine) {
  27824. this.onBeforePhysicsObservable.notifyObservers(this);
  27825. this._physicsEngine._step(deltaTime / 1000.0);
  27826. this.onAfterPhysicsObservable.notifyObservers(this);
  27827. }
  27828. }
  27829. // update gamepad manager
  27830. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27831. this._gamepadManager._checkGamepadsStatus();
  27832. }
  27833. // Update Cameras
  27834. if (updateCameras) {
  27835. if (this.activeCameras.length > 0) {
  27836. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27837. var camera = this.activeCameras[cameraIndex];
  27838. camera.update();
  27839. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27840. // rig cameras
  27841. for (var index = 0; index < camera._rigCameras.length; index++) {
  27842. camera._rigCameras[index].update();
  27843. }
  27844. }
  27845. }
  27846. }
  27847. else if (this.activeCamera) {
  27848. this.activeCamera.update();
  27849. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27850. // rig cameras
  27851. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27852. this.activeCamera._rigCameras[index].update();
  27853. }
  27854. }
  27855. }
  27856. }
  27857. // Before render
  27858. this.onBeforeRenderObservable.notifyObservers(this);
  27859. // Customs render targets
  27860. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27861. var engine = this.getEngine();
  27862. var currentActiveCamera = this.activeCamera;
  27863. if (this.renderTargetsEnabled) {
  27864. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27865. this._intermediateRendering = true;
  27866. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27867. var renderTarget = this.customRenderTargets[customIndex];
  27868. if (renderTarget._shouldRender()) {
  27869. this._renderId++;
  27870. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27871. if (!this.activeCamera)
  27872. throw new Error("Active camera not set");
  27873. // Viewport
  27874. engine.setViewport(this.activeCamera.viewport);
  27875. // Camera
  27876. this.updateTransformMatrix();
  27877. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27878. }
  27879. }
  27880. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27881. this._intermediateRendering = false;
  27882. this._renderId++;
  27883. }
  27884. // Restore back buffer
  27885. if (this.customRenderTargets.length > 0) {
  27886. engine.restoreDefaultFramebuffer();
  27887. }
  27888. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27889. this.activeCamera = currentActiveCamera;
  27890. // Procedural textures
  27891. if (this.proceduralTexturesEnabled) {
  27892. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27893. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27894. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27895. if (proceduralTexture._shouldRender()) {
  27896. proceduralTexture.render();
  27897. }
  27898. }
  27899. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27900. }
  27901. // Clear
  27902. if (this.autoClearDepthAndStencil || this.autoClear) {
  27903. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27904. }
  27905. // Shadows
  27906. if (this.shadowsEnabled) {
  27907. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27908. var light = this.lights[lightIndex];
  27909. var shadowGenerator = light.getShadowGenerator();
  27910. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27911. var shadowMap = (shadowGenerator.getShadowMap());
  27912. if (this.textures.indexOf(shadowMap) !== -1) {
  27913. this._renderTargets.push(shadowMap);
  27914. }
  27915. }
  27916. }
  27917. }
  27918. // Depth renderer
  27919. for (var key in this._depthRenderer) {
  27920. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27921. }
  27922. // Geometry renderer
  27923. if (this._geometryBufferRenderer) {
  27924. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27925. }
  27926. // RenderPipeline
  27927. if (this._postProcessRenderPipelineManager) {
  27928. this._postProcessRenderPipelineManager.update();
  27929. }
  27930. // Multi-cameras?
  27931. if (this.activeCameras.length > 0) {
  27932. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27933. if (cameraIndex > 0) {
  27934. this._engine.clear(null, false, true, true);
  27935. }
  27936. this._processSubCameras(this.activeCameras[cameraIndex]);
  27937. }
  27938. }
  27939. else {
  27940. if (!this.activeCamera) {
  27941. throw new Error("No camera defined");
  27942. }
  27943. this._processSubCameras(this.activeCamera);
  27944. }
  27945. // Intersection checks
  27946. this._checkIntersections();
  27947. // Update the audio listener attached to the camera
  27948. if (BABYLON.AudioEngine) {
  27949. this._updateAudioParameters();
  27950. }
  27951. // After render
  27952. if (this.afterRender) {
  27953. this.afterRender();
  27954. }
  27955. this.onAfterRenderObservable.notifyObservers(this);
  27956. // Cleaning
  27957. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27958. var data = this._toBeDisposed.data[index];
  27959. if (data) {
  27960. data.dispose();
  27961. }
  27962. this._toBeDisposed[index] = null;
  27963. }
  27964. this._toBeDisposed.reset();
  27965. if (this.dumpNextRenderTargets) {
  27966. this.dumpNextRenderTargets = false;
  27967. }
  27968. this._activeBones.addCount(0, true);
  27969. this._activeIndices.addCount(0, true);
  27970. this._activeParticles.addCount(0, true);
  27971. };
  27972. Scene.prototype._updateAudioParameters = function () {
  27973. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27974. return;
  27975. }
  27976. var listeningCamera;
  27977. var audioEngine = BABYLON.Engine.audioEngine;
  27978. if (this.activeCameras.length > 0) {
  27979. listeningCamera = this.activeCameras[0];
  27980. }
  27981. else {
  27982. listeningCamera = this.activeCamera;
  27983. }
  27984. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27985. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27986. // for VR cameras
  27987. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27988. listeningCamera = listeningCamera.rigCameras[0];
  27989. }
  27990. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27991. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27992. cameraDirection.normalize();
  27993. // To avoid some errors on GearVR
  27994. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27995. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27996. }
  27997. var i;
  27998. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27999. var sound = this.mainSoundTrack.soundCollection[i];
  28000. if (sound.useCustomAttenuation) {
  28001. sound.updateDistanceFromListener();
  28002. }
  28003. }
  28004. for (i = 0; i < this.soundTracks.length; i++) {
  28005. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28006. sound = this.soundTracks[i].soundCollection[j];
  28007. if (sound.useCustomAttenuation) {
  28008. sound.updateDistanceFromListener();
  28009. }
  28010. }
  28011. }
  28012. }
  28013. };
  28014. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28015. // Audio
  28016. /**
  28017. * Gets or sets if audio support is enabled
  28018. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28019. */
  28020. get: function () {
  28021. return this._audioEnabled;
  28022. },
  28023. set: function (value) {
  28024. this._audioEnabled = value;
  28025. if (BABYLON.AudioEngine) {
  28026. if (this._audioEnabled) {
  28027. this._enableAudio();
  28028. }
  28029. else {
  28030. this._disableAudio();
  28031. }
  28032. }
  28033. },
  28034. enumerable: true,
  28035. configurable: true
  28036. });
  28037. Scene.prototype._disableAudio = function () {
  28038. var i;
  28039. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28040. this.mainSoundTrack.soundCollection[i].pause();
  28041. }
  28042. for (i = 0; i < this.soundTracks.length; i++) {
  28043. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28044. this.soundTracks[i].soundCollection[j].pause();
  28045. }
  28046. }
  28047. };
  28048. Scene.prototype._enableAudio = function () {
  28049. var i;
  28050. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28051. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28052. this.mainSoundTrack.soundCollection[i].play();
  28053. }
  28054. }
  28055. for (i = 0; i < this.soundTracks.length; i++) {
  28056. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28057. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28058. this.soundTracks[i].soundCollection[j].play();
  28059. }
  28060. }
  28061. }
  28062. };
  28063. Object.defineProperty(Scene.prototype, "headphone", {
  28064. /**
  28065. * Gets or sets if audio will be output to headphones
  28066. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28067. */
  28068. get: function () {
  28069. return this._headphone;
  28070. },
  28071. set: function (value) {
  28072. this._headphone = value;
  28073. if (BABYLON.AudioEngine) {
  28074. if (this._headphone) {
  28075. this._switchAudioModeForHeadphones();
  28076. }
  28077. else {
  28078. this._switchAudioModeForNormalSpeakers();
  28079. }
  28080. }
  28081. },
  28082. enumerable: true,
  28083. configurable: true
  28084. });
  28085. Scene.prototype._switchAudioModeForHeadphones = function () {
  28086. this.mainSoundTrack.switchPanningModelToHRTF();
  28087. for (var i = 0; i < this.soundTracks.length; i++) {
  28088. this.soundTracks[i].switchPanningModelToHRTF();
  28089. }
  28090. };
  28091. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28092. this.mainSoundTrack.switchPanningModelToEqualPower();
  28093. for (var i = 0; i < this.soundTracks.length; i++) {
  28094. this.soundTracks[i].switchPanningModelToEqualPower();
  28095. }
  28096. };
  28097. /**
  28098. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28099. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28100. * @returns the created depth renderer
  28101. */
  28102. Scene.prototype.enableDepthRenderer = function (camera) {
  28103. camera = camera || this.activeCamera;
  28104. if (!camera) {
  28105. throw "No camera available to enable depth renderer";
  28106. }
  28107. if (!this._depthRenderer[camera.id]) {
  28108. var textureType = 0;
  28109. if (this._engine.getCaps().textureHalfFloatRender) {
  28110. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28111. }
  28112. else if (this._engine.getCaps().textureFloatRender) {
  28113. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28114. }
  28115. else {
  28116. throw "Depth renderer does not support int texture type";
  28117. }
  28118. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28119. }
  28120. return this._depthRenderer[camera.id];
  28121. };
  28122. /**
  28123. * Disables a depth renderer for a given camera
  28124. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28125. */
  28126. Scene.prototype.disableDepthRenderer = function (camera) {
  28127. camera = camera || this.activeCamera;
  28128. if (!camera || !this._depthRenderer[camera.id]) {
  28129. return;
  28130. }
  28131. this._depthRenderer[camera.id].dispose();
  28132. delete this._depthRenderer[camera.id];
  28133. };
  28134. /**
  28135. * Enables a GeometryBufferRender and associates it with the scene
  28136. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28137. * @returns the GeometryBufferRenderer
  28138. */
  28139. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28140. if (ratio === void 0) { ratio = 1; }
  28141. if (this._geometryBufferRenderer) {
  28142. return this._geometryBufferRenderer;
  28143. }
  28144. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28145. if (!this._geometryBufferRenderer.isSupported) {
  28146. this._geometryBufferRenderer = null;
  28147. }
  28148. return this._geometryBufferRenderer;
  28149. };
  28150. /**
  28151. * Disables the GeometryBufferRender associated with the scene
  28152. */
  28153. Scene.prototype.disableGeometryBufferRenderer = function () {
  28154. if (!this._geometryBufferRenderer) {
  28155. return;
  28156. }
  28157. this._geometryBufferRenderer.dispose();
  28158. this._geometryBufferRenderer = null;
  28159. };
  28160. /**
  28161. * Freeze all materials
  28162. * A frozen material will not be updatable but should be faster to render
  28163. */
  28164. Scene.prototype.freezeMaterials = function () {
  28165. for (var i = 0; i < this.materials.length; i++) {
  28166. this.materials[i].freeze();
  28167. }
  28168. };
  28169. /**
  28170. * Unfreeze all materials
  28171. * A frozen material will not be updatable but should be faster to render
  28172. */
  28173. Scene.prototype.unfreezeMaterials = function () {
  28174. for (var i = 0; i < this.materials.length; i++) {
  28175. this.materials[i].unfreeze();
  28176. }
  28177. };
  28178. /**
  28179. * Releases all held ressources
  28180. */
  28181. Scene.prototype.dispose = function () {
  28182. this.beforeRender = null;
  28183. this.afterRender = null;
  28184. this.skeletons = [];
  28185. this.morphTargetManagers = [];
  28186. this.importedMeshesFiles = new Array();
  28187. this.stopAllAnimations();
  28188. this.resetCachedMaterial();
  28189. for (var key in this._depthRenderer) {
  28190. this._depthRenderer[key].dispose();
  28191. }
  28192. if (this._gamepadManager) {
  28193. this._gamepadManager.dispose();
  28194. this._gamepadManager = null;
  28195. }
  28196. // Smart arrays
  28197. if (this.activeCamera) {
  28198. this.activeCamera._activeMeshes.dispose();
  28199. this.activeCamera = null;
  28200. }
  28201. this._activeMeshes.dispose();
  28202. this._renderingManager.dispose();
  28203. this._processedMaterials.dispose();
  28204. this._activeParticleSystems.dispose();
  28205. this._activeSkeletons.dispose();
  28206. this._softwareSkinnedMeshes.dispose();
  28207. this._renderTargets.dispose();
  28208. this._registeredForLateAnimationBindings.dispose();
  28209. if (this._boundingBoxRenderer) {
  28210. this._boundingBoxRenderer.dispose();
  28211. }
  28212. this._meshesForIntersections.dispose();
  28213. this._toBeDisposed.dispose();
  28214. // Abort active requests
  28215. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28216. var request = _a[_i];
  28217. request.abort();
  28218. }
  28219. // Debug layer
  28220. if (this._debugLayer) {
  28221. this._debugLayer.hide();
  28222. }
  28223. // Events
  28224. this.onDisposeObservable.notifyObservers(this);
  28225. this.onDisposeObservable.clear();
  28226. this.onBeforeRenderObservable.clear();
  28227. this.onAfterRenderObservable.clear();
  28228. this.onBeforeRenderTargetsRenderObservable.clear();
  28229. this.onAfterRenderTargetsRenderObservable.clear();
  28230. this.onAfterStepObservable.clear();
  28231. this.onBeforeStepObservable.clear();
  28232. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28233. this.onAfterActiveMeshesEvaluationObservable.clear();
  28234. this.onBeforeParticlesRenderingObservable.clear();
  28235. this.onAfterParticlesRenderingObservable.clear();
  28236. this.onBeforeSpritesRenderingObservable.clear();
  28237. this.onAfterSpritesRenderingObservable.clear();
  28238. this.onBeforeDrawPhaseObservable.clear();
  28239. this.onAfterDrawPhaseObservable.clear();
  28240. this.onBeforePhysicsObservable.clear();
  28241. this.onAfterPhysicsObservable.clear();
  28242. this.onBeforeAnimationsObservable.clear();
  28243. this.onAfterAnimationsObservable.clear();
  28244. this.onDataLoadedObservable.clear();
  28245. this.detachControl();
  28246. // Release sounds & sounds tracks
  28247. if (BABYLON.AudioEngine) {
  28248. this.disposeSounds();
  28249. }
  28250. // VR Helper
  28251. if (this.VRHelper) {
  28252. this.VRHelper.dispose();
  28253. }
  28254. // Detach cameras
  28255. var canvas = this._engine.getRenderingCanvas();
  28256. if (canvas) {
  28257. var index;
  28258. for (index = 0; index < this.cameras.length; index++) {
  28259. this.cameras[index].detachControl(canvas);
  28260. }
  28261. }
  28262. // Release animation groups
  28263. while (this.animationGroups.length) {
  28264. this.animationGroups[0].dispose();
  28265. }
  28266. // Release lights
  28267. while (this.lights.length) {
  28268. this.lights[0].dispose();
  28269. }
  28270. // Release meshes
  28271. while (this.meshes.length) {
  28272. this.meshes[0].dispose(true);
  28273. }
  28274. while (this.transformNodes.length) {
  28275. this.removeTransformNode(this.transformNodes[0]);
  28276. }
  28277. // Release cameras
  28278. while (this.cameras.length) {
  28279. this.cameras[0].dispose();
  28280. }
  28281. // Release materials
  28282. if (this.defaultMaterial) {
  28283. this.defaultMaterial.dispose();
  28284. }
  28285. while (this.multiMaterials.length) {
  28286. this.multiMaterials[0].dispose();
  28287. }
  28288. while (this.materials.length) {
  28289. this.materials[0].dispose();
  28290. }
  28291. // Release particles
  28292. while (this.particleSystems.length) {
  28293. this.particleSystems[0].dispose();
  28294. }
  28295. // Release sprites
  28296. while (this.spriteManagers.length) {
  28297. this.spriteManagers[0].dispose();
  28298. }
  28299. // Release postProcesses
  28300. while (this.postProcesses.length) {
  28301. this.postProcesses[0].dispose();
  28302. }
  28303. // Release layers
  28304. while (this.layers.length) {
  28305. this.layers[0].dispose();
  28306. }
  28307. while (this.effectLayers.length) {
  28308. this.effectLayers[0].dispose();
  28309. }
  28310. // Release textures
  28311. while (this.textures.length) {
  28312. this.textures[0].dispose();
  28313. }
  28314. // Release UBO
  28315. this._sceneUbo.dispose();
  28316. if (this._alternateSceneUbo) {
  28317. this._alternateSceneUbo.dispose();
  28318. }
  28319. // Post-processes
  28320. this.postProcessManager.dispose();
  28321. if (this._postProcessRenderPipelineManager) {
  28322. this._postProcessRenderPipelineManager.dispose();
  28323. }
  28324. // Physics
  28325. if (this._physicsEngine) {
  28326. this.disablePhysicsEngine();
  28327. }
  28328. // Remove from engine
  28329. index = this._engine.scenes.indexOf(this);
  28330. if (index > -1) {
  28331. this._engine.scenes.splice(index, 1);
  28332. }
  28333. this._engine.wipeCaches(true);
  28334. this._isDisposed = true;
  28335. };
  28336. Object.defineProperty(Scene.prototype, "isDisposed", {
  28337. /**
  28338. * Gets if the scene is already disposed
  28339. */
  28340. get: function () {
  28341. return this._isDisposed;
  28342. },
  28343. enumerable: true,
  28344. configurable: true
  28345. });
  28346. /**
  28347. * Releases sounds & soundtracks
  28348. */
  28349. Scene.prototype.disposeSounds = function () {
  28350. if (!this._mainSoundTrack) {
  28351. return;
  28352. }
  28353. this.mainSoundTrack.dispose();
  28354. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28355. this.soundTracks[scIndex].dispose();
  28356. }
  28357. };
  28358. /**
  28359. * Call this function to reduce memory footprint of the scene.
  28360. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28361. */
  28362. Scene.prototype.clearCachedVertexData = function () {
  28363. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28364. var mesh = this.meshes[meshIndex];
  28365. var geometry = mesh.geometry;
  28366. if (geometry) {
  28367. geometry._indices = [];
  28368. for (var vbName in geometry._vertexBuffers) {
  28369. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28370. continue;
  28371. }
  28372. geometry._vertexBuffers[vbName]._buffer._data = null;
  28373. }
  28374. }
  28375. }
  28376. };
  28377. /**
  28378. * This function will remove the local cached buffer data from texture.
  28379. * It will save memory but will prevent the texture from being rebuilt
  28380. */
  28381. Scene.prototype.cleanCachedTextureBuffer = function () {
  28382. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28383. var baseTexture = _a[_i];
  28384. var buffer = baseTexture._buffer;
  28385. if (buffer) {
  28386. baseTexture._buffer = null;
  28387. }
  28388. }
  28389. };
  28390. // Octrees
  28391. /**
  28392. * Get the world extend vectors with an optional filter
  28393. *
  28394. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28395. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28396. */
  28397. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28398. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28399. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28400. filterPredicate = filterPredicate || (function () { return true; });
  28401. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28402. mesh.computeWorldMatrix(true);
  28403. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28404. return;
  28405. }
  28406. var boundingInfo = mesh.getBoundingInfo();
  28407. var minBox = boundingInfo.boundingBox.minimumWorld;
  28408. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28409. BABYLON.Tools.CheckExtends(minBox, min, max);
  28410. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28411. });
  28412. return {
  28413. min: min,
  28414. max: max
  28415. };
  28416. };
  28417. /**
  28418. * Creates or updates the octree used to boost selection (picking)
  28419. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28420. * @param maxCapacity defines the maximum capacity per leaf
  28421. * @param maxDepth defines the maximum depth of the octree
  28422. * @returns an octree of AbstractMesh
  28423. */
  28424. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28425. if (maxCapacity === void 0) { maxCapacity = 64; }
  28426. if (maxDepth === void 0) { maxDepth = 2; }
  28427. if (!this._selectionOctree) {
  28428. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28429. }
  28430. var worldExtends = this.getWorldExtends();
  28431. // Update octree
  28432. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28433. return this._selectionOctree;
  28434. };
  28435. // Picking
  28436. /**
  28437. * Creates a ray that can be used to pick in the scene
  28438. * @param x defines the x coordinate of the origin (on-screen)
  28439. * @param y defines the y coordinate of the origin (on-screen)
  28440. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28441. * @param camera defines the camera to use for the picking
  28442. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28443. * @returns a Ray
  28444. */
  28445. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28446. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28447. var result = BABYLON.Ray.Zero();
  28448. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28449. return result;
  28450. };
  28451. /**
  28452. * Creates a ray that can be used to pick in the scene
  28453. * @param x defines the x coordinate of the origin (on-screen)
  28454. * @param y defines the y coordinate of the origin (on-screen)
  28455. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28456. * @param result defines the ray where to store the picking ray
  28457. * @param camera defines the camera to use for the picking
  28458. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28459. * @returns the current scene
  28460. */
  28461. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28462. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28463. var engine = this._engine;
  28464. if (!camera) {
  28465. if (!this.activeCamera)
  28466. throw new Error("Active camera not set");
  28467. camera = this.activeCamera;
  28468. }
  28469. var cameraViewport = camera.viewport;
  28470. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28471. // Moving coordinates to local viewport world
  28472. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28473. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28474. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28475. return this;
  28476. };
  28477. /**
  28478. * Creates a ray that can be used to pick in the scene
  28479. * @param x defines the x coordinate of the origin (on-screen)
  28480. * @param y defines the y coordinate of the origin (on-screen)
  28481. * @param camera defines the camera to use for the picking
  28482. * @returns a Ray
  28483. */
  28484. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28485. var result = BABYLON.Ray.Zero();
  28486. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28487. return result;
  28488. };
  28489. /**
  28490. * Creates a ray that can be used to pick in the scene
  28491. * @param x defines the x coordinate of the origin (on-screen)
  28492. * @param y defines the y coordinate of the origin (on-screen)
  28493. * @param result defines the ray where to store the picking ray
  28494. * @param camera defines the camera to use for the picking
  28495. * @returns the current scene
  28496. */
  28497. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28498. if (!BABYLON.PickingInfo) {
  28499. return this;
  28500. }
  28501. var engine = this._engine;
  28502. if (!camera) {
  28503. if (!this.activeCamera)
  28504. throw new Error("Active camera not set");
  28505. camera = this.activeCamera;
  28506. }
  28507. var cameraViewport = camera.viewport;
  28508. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28509. var identity = BABYLON.Matrix.Identity();
  28510. // Moving coordinates to local viewport world
  28511. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28512. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28513. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28514. return this;
  28515. };
  28516. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28517. if (!BABYLON.PickingInfo) {
  28518. return null;
  28519. }
  28520. var pickingInfo = null;
  28521. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28522. var mesh = this.meshes[meshIndex];
  28523. if (predicate) {
  28524. if (!predicate(mesh)) {
  28525. continue;
  28526. }
  28527. }
  28528. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28529. continue;
  28530. }
  28531. var world = mesh.getWorldMatrix();
  28532. var ray = rayFunction(world);
  28533. var result = mesh.intersects(ray, fastCheck);
  28534. if (!result || !result.hit)
  28535. continue;
  28536. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28537. continue;
  28538. pickingInfo = result;
  28539. if (fastCheck) {
  28540. break;
  28541. }
  28542. }
  28543. return pickingInfo || new BABYLON.PickingInfo();
  28544. };
  28545. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28546. if (!BABYLON.PickingInfo) {
  28547. return null;
  28548. }
  28549. var pickingInfos = new Array();
  28550. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28551. var mesh = this.meshes[meshIndex];
  28552. if (predicate) {
  28553. if (!predicate(mesh)) {
  28554. continue;
  28555. }
  28556. }
  28557. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28558. continue;
  28559. }
  28560. var world = mesh.getWorldMatrix();
  28561. var ray = rayFunction(world);
  28562. var result = mesh.intersects(ray, false);
  28563. if (!result || !result.hit)
  28564. continue;
  28565. pickingInfos.push(result);
  28566. }
  28567. return pickingInfos;
  28568. };
  28569. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28570. if (!BABYLON.PickingInfo) {
  28571. return null;
  28572. }
  28573. var pickingInfo = null;
  28574. if (!camera) {
  28575. if (!this.activeCamera) {
  28576. return null;
  28577. }
  28578. camera = this.activeCamera;
  28579. }
  28580. if (this.spriteManagers.length > 0) {
  28581. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28582. var spriteManager = this.spriteManagers[spriteIndex];
  28583. if (!spriteManager.isPickable) {
  28584. continue;
  28585. }
  28586. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28587. if (!result || !result.hit)
  28588. continue;
  28589. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28590. continue;
  28591. pickingInfo = result;
  28592. if (fastCheck) {
  28593. break;
  28594. }
  28595. }
  28596. }
  28597. return pickingInfo || new BABYLON.PickingInfo();
  28598. };
  28599. /** Launch a ray to try to pick a mesh in the scene
  28600. * @param x position on screen
  28601. * @param y position on screen
  28602. * @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
  28603. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28604. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28605. * @returns a PickingInfo
  28606. */
  28607. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28608. var _this = this;
  28609. if (!BABYLON.PickingInfo) {
  28610. return null;
  28611. }
  28612. var result = this._internalPick(function (world) {
  28613. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28614. return _this._tempPickingRay;
  28615. }, predicate, fastCheck);
  28616. if (result) {
  28617. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28618. }
  28619. return result;
  28620. };
  28621. /** Launch a ray to try to pick a sprite in the scene
  28622. * @param x position on screen
  28623. * @param y position on screen
  28624. * @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
  28625. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28626. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28627. * @returns a PickingInfo
  28628. */
  28629. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28630. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28631. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28632. };
  28633. /** Use the given ray to pick a mesh in the scene
  28634. * @param ray The ray to use to pick meshes
  28635. * @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
  28636. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28637. * @returns a PickingInfo
  28638. */
  28639. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28640. var _this = this;
  28641. var result = this._internalPick(function (world) {
  28642. if (!_this._pickWithRayInverseMatrix) {
  28643. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28644. }
  28645. world.invertToRef(_this._pickWithRayInverseMatrix);
  28646. if (!_this._cachedRayForTransform) {
  28647. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28648. }
  28649. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28650. return _this._cachedRayForTransform;
  28651. }, predicate, fastCheck);
  28652. if (result) {
  28653. result.ray = ray;
  28654. }
  28655. return result;
  28656. };
  28657. /**
  28658. * Launch a ray to try to pick a mesh in the scene
  28659. * @param x X position on screen
  28660. * @param y Y position on screen
  28661. * @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
  28662. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28663. * @returns an array of PickingInfo
  28664. */
  28665. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28666. var _this = this;
  28667. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28668. };
  28669. /**
  28670. * Launch a ray to try to pick a mesh in the scene
  28671. * @param ray Ray to use
  28672. * @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
  28673. * @returns an array of PickingInfo
  28674. */
  28675. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28676. var _this = this;
  28677. return this._internalMultiPick(function (world) {
  28678. if (!_this._pickWithRayInverseMatrix) {
  28679. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28680. }
  28681. world.invertToRef(_this._pickWithRayInverseMatrix);
  28682. if (!_this._cachedRayForTransform) {
  28683. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28684. }
  28685. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28686. return _this._cachedRayForTransform;
  28687. }, predicate);
  28688. };
  28689. /**
  28690. * Force the value of meshUnderPointer
  28691. * @param mesh defines the mesh to use
  28692. */
  28693. Scene.prototype.setPointerOverMesh = function (mesh) {
  28694. if (this._pointerOverMesh === mesh) {
  28695. return;
  28696. }
  28697. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28698. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28699. }
  28700. this._pointerOverMesh = mesh;
  28701. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28702. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28703. }
  28704. };
  28705. /**
  28706. * Gets the mesh under the pointer
  28707. * @returns a Mesh or null if no mesh is under the pointer
  28708. */
  28709. Scene.prototype.getPointerOverMesh = function () {
  28710. return this._pointerOverMesh;
  28711. };
  28712. /**
  28713. * Force the sprite under the pointer
  28714. * @param sprite defines the sprite to use
  28715. */
  28716. Scene.prototype.setPointerOverSprite = function (sprite) {
  28717. if (this._pointerOverSprite === sprite) {
  28718. return;
  28719. }
  28720. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28721. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28722. }
  28723. this._pointerOverSprite = sprite;
  28724. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28725. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28726. }
  28727. };
  28728. /**
  28729. * Gets the sprite under the pointer
  28730. * @returns a Sprite or null if no sprite is under the pointer
  28731. */
  28732. Scene.prototype.getPointerOverSprite = function () {
  28733. return this._pointerOverSprite;
  28734. };
  28735. // Physics
  28736. /**
  28737. * Gets the current physics engine
  28738. * @returns a PhysicsEngine or null if none attached
  28739. */
  28740. Scene.prototype.getPhysicsEngine = function () {
  28741. return this._physicsEngine;
  28742. };
  28743. /**
  28744. * Enables physics to the current scene
  28745. * @param gravity defines the scene's gravity for the physics engine
  28746. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28747. * @return a boolean indicating if the physics engine was initialized
  28748. */
  28749. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28750. if (gravity === void 0) { gravity = null; }
  28751. if (this._physicsEngine) {
  28752. return true;
  28753. }
  28754. try {
  28755. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28756. return true;
  28757. }
  28758. catch (e) {
  28759. BABYLON.Tools.Error(e.message);
  28760. return false;
  28761. }
  28762. };
  28763. /**
  28764. * Disables and disposes the physics engine associated with the scene
  28765. */
  28766. Scene.prototype.disablePhysicsEngine = function () {
  28767. if (!this._physicsEngine) {
  28768. return;
  28769. }
  28770. this._physicsEngine.dispose();
  28771. this._physicsEngine = null;
  28772. };
  28773. /**
  28774. * Gets a boolean indicating if there is an active physics engine
  28775. * @returns a boolean indicating if there is an active physics engine
  28776. */
  28777. Scene.prototype.isPhysicsEnabled = function () {
  28778. return this._physicsEngine !== undefined;
  28779. };
  28780. /**
  28781. * Deletes a physics compound impostor
  28782. * @param compound defines the compound to delete
  28783. */
  28784. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28785. var mesh = compound.parts[0].mesh;
  28786. if (mesh.physicsImpostor) {
  28787. mesh.physicsImpostor.dispose( /*true*/);
  28788. mesh.physicsImpostor = null;
  28789. }
  28790. };
  28791. // Misc.
  28792. /** @hidden */
  28793. Scene.prototype._rebuildGeometries = function () {
  28794. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28795. var geometry = _a[_i];
  28796. geometry._rebuild();
  28797. }
  28798. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28799. var mesh = _c[_b];
  28800. mesh._rebuild();
  28801. }
  28802. if (this.postProcessManager) {
  28803. this.postProcessManager._rebuild();
  28804. }
  28805. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28806. var layer = _e[_d];
  28807. layer._rebuild();
  28808. }
  28809. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28810. var effectLayer = _g[_f];
  28811. effectLayer._rebuild();
  28812. }
  28813. if (this._boundingBoxRenderer) {
  28814. this._boundingBoxRenderer._rebuild();
  28815. }
  28816. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28817. var system = _j[_h];
  28818. system.rebuild();
  28819. }
  28820. if (this._postProcessRenderPipelineManager) {
  28821. this._postProcessRenderPipelineManager._rebuild();
  28822. }
  28823. };
  28824. /** @hidden */
  28825. Scene.prototype._rebuildTextures = function () {
  28826. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28827. var texture = _a[_i];
  28828. texture._rebuild();
  28829. }
  28830. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28831. };
  28832. /**
  28833. * Creates a default light for the scene.
  28834. * @param replace Whether to replace the existing lights in the scene.
  28835. */
  28836. Scene.prototype.createDefaultLight = function (replace) {
  28837. if (replace === void 0) { replace = false; }
  28838. // Dispose existing light in replace mode.
  28839. if (replace) {
  28840. if (this.lights) {
  28841. for (var i = 0; i < this.lights.length; i++) {
  28842. this.lights[i].dispose();
  28843. }
  28844. }
  28845. }
  28846. // Light
  28847. if (this.lights.length === 0) {
  28848. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28849. }
  28850. };
  28851. /**
  28852. * Creates a default camera for the scene.
  28853. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28854. * @param replace Whether to replace the existing active camera in the scene.
  28855. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28856. */
  28857. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28858. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28859. if (replace === void 0) { replace = false; }
  28860. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28861. // Dispose existing camera in replace mode.
  28862. if (replace) {
  28863. if (this.activeCamera) {
  28864. this.activeCamera.dispose();
  28865. this.activeCamera = null;
  28866. }
  28867. }
  28868. // Camera
  28869. if (!this.activeCamera) {
  28870. var worldExtends = this.getWorldExtends();
  28871. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28872. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28873. var camera;
  28874. var radius = worldSize.length() * 1.5;
  28875. // empty scene scenario!
  28876. if (!isFinite(radius)) {
  28877. radius = 1;
  28878. worldCenter.copyFromFloats(0, 0, 0);
  28879. }
  28880. if (createArcRotateCamera) {
  28881. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28882. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28883. arcRotateCamera.wheelPrecision = 100 / radius;
  28884. camera = arcRotateCamera;
  28885. }
  28886. else {
  28887. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28888. freeCamera.setTarget(worldCenter);
  28889. camera = freeCamera;
  28890. }
  28891. camera.minZ = radius * 0.01;
  28892. camera.maxZ = radius * 1000;
  28893. camera.speed = radius * 0.2;
  28894. this.activeCamera = camera;
  28895. var canvas = this.getEngine().getRenderingCanvas();
  28896. if (attachCameraControls && canvas) {
  28897. camera.attachControl(canvas);
  28898. }
  28899. }
  28900. };
  28901. /**
  28902. * Creates a default camera and a default light
  28903. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28904. * @param replace defines if the camera and/or light will replace the existing ones
  28905. * @param attachCameraControls defines if attachControl will be called on the new camera
  28906. */
  28907. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28908. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28909. if (replace === void 0) { replace = false; }
  28910. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28911. this.createDefaultLight(replace);
  28912. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28913. };
  28914. /**
  28915. * Creates a new sky box
  28916. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28917. * @param environmentTexture defines the texture to use as environment texture
  28918. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28919. * @param scale defines the overall scale of the skybox
  28920. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28921. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28922. * @returns a new mesh holding the sky box
  28923. */
  28924. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28925. if (pbr === void 0) { pbr = false; }
  28926. if (scale === void 0) { scale = 1000; }
  28927. if (blur === void 0) { blur = 0; }
  28928. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28929. if (!environmentTexture) {
  28930. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28931. return null;
  28932. }
  28933. if (setGlobalEnvTexture) {
  28934. if (environmentTexture) {
  28935. this.environmentTexture = environmentTexture;
  28936. }
  28937. }
  28938. // Skybox
  28939. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28940. if (pbr) {
  28941. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28942. hdrSkyboxMaterial.backFaceCulling = false;
  28943. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28944. if (hdrSkyboxMaterial.reflectionTexture) {
  28945. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28946. }
  28947. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28948. hdrSkyboxMaterial.disableLighting = true;
  28949. hdrSkyboxMaterial.twoSidedLighting = true;
  28950. hdrSkybox.infiniteDistance = true;
  28951. hdrSkybox.material = hdrSkyboxMaterial;
  28952. }
  28953. else {
  28954. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28955. skyboxMaterial.backFaceCulling = false;
  28956. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28957. if (skyboxMaterial.reflectionTexture) {
  28958. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28959. }
  28960. skyboxMaterial.disableLighting = true;
  28961. hdrSkybox.infiniteDistance = true;
  28962. hdrSkybox.material = skyboxMaterial;
  28963. }
  28964. return hdrSkybox;
  28965. };
  28966. /**
  28967. * Creates a new environment
  28968. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28969. * @param options defines the options you can use to configure the environment
  28970. * @returns the new EnvironmentHelper
  28971. */
  28972. Scene.prototype.createDefaultEnvironment = function (options) {
  28973. if (BABYLON.EnvironmentHelper) {
  28974. return new BABYLON.EnvironmentHelper(options, this);
  28975. }
  28976. return null;
  28977. };
  28978. /**
  28979. * Creates a new VREXperienceHelper
  28980. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28981. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28982. * @returns a new VREXperienceHelper
  28983. */
  28984. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28985. if (webVROptions === void 0) { webVROptions = {}; }
  28986. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28987. };
  28988. // Tags
  28989. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28990. if (tagsQuery === undefined) {
  28991. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28992. return list;
  28993. }
  28994. var listByTags = [];
  28995. forEach = forEach || (function (item) { return; });
  28996. for (var i in list) {
  28997. var item = list[i];
  28998. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28999. listByTags.push(item);
  29000. forEach(item);
  29001. }
  29002. }
  29003. return listByTags;
  29004. };
  29005. /**
  29006. * Get a list of meshes by tags
  29007. * @param tagsQuery defines the tags query to use
  29008. * @param forEach defines a predicate used to filter results
  29009. * @returns an array of Mesh
  29010. */
  29011. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29012. return this._getByTags(this.meshes, tagsQuery, forEach);
  29013. };
  29014. /**
  29015. * Get a list of cameras by tags
  29016. * @param tagsQuery defines the tags query to use
  29017. * @param forEach defines a predicate used to filter results
  29018. * @returns an array of Camera
  29019. */
  29020. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29021. return this._getByTags(this.cameras, tagsQuery, forEach);
  29022. };
  29023. /**
  29024. * Get a list of lights by tags
  29025. * @param tagsQuery defines the tags query to use
  29026. * @param forEach defines a predicate used to filter results
  29027. * @returns an array of Light
  29028. */
  29029. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29030. return this._getByTags(this.lights, tagsQuery, forEach);
  29031. };
  29032. /**
  29033. * Get a list of materials by tags
  29034. * @param tagsQuery defines the tags query to use
  29035. * @param forEach defines a predicate used to filter results
  29036. * @returns an array of Material
  29037. */
  29038. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29039. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29040. };
  29041. /**
  29042. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29043. * This allowed control for front to back rendering or reversly depending of the special needs.
  29044. *
  29045. * @param renderingGroupId The rendering group id corresponding to its index
  29046. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29047. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29048. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29049. */
  29050. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29051. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29052. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29053. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29054. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29055. };
  29056. /**
  29057. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29058. *
  29059. * @param renderingGroupId The rendering group id corresponding to its index
  29060. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29061. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29062. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29063. */
  29064. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29065. if (depth === void 0) { depth = true; }
  29066. if (stencil === void 0) { stencil = true; }
  29067. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29068. };
  29069. /**
  29070. * Will flag all materials as dirty to trigger new shader compilation
  29071. * @param flag defines the flag used to specify which material part must be marked as dirty
  29072. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29073. */
  29074. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29075. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29076. var material = _a[_i];
  29077. if (predicate && !predicate(material)) {
  29078. continue;
  29079. }
  29080. material.markAsDirty(flag);
  29081. }
  29082. };
  29083. /** @hidden */
  29084. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29085. var _this = this;
  29086. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29087. this._activeRequests.push(request);
  29088. request.onCompleteObservable.add(function (request) {
  29089. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29090. });
  29091. return request;
  29092. };
  29093. /** @hidden */
  29094. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29095. var _this = this;
  29096. return new Promise(function (resolve, reject) {
  29097. _this._loadFile(url, function (data) {
  29098. resolve(data);
  29099. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29100. reject(exception);
  29101. });
  29102. });
  29103. };
  29104. // Statics
  29105. Scene._FOGMODE_NONE = 0;
  29106. Scene._FOGMODE_EXP = 1;
  29107. Scene._FOGMODE_EXP2 = 2;
  29108. Scene._FOGMODE_LINEAR = 3;
  29109. Scene._uniqueIdCounter = 0;
  29110. /**
  29111. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29112. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29113. */
  29114. Scene.MinDeltaTime = 1.0;
  29115. /**
  29116. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29117. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29118. */
  29119. Scene.MaxDeltaTime = 1000.0;
  29120. /** The distance in pixel that you have to move to prevent some events */
  29121. Scene.DragMovementThreshold = 10; // in pixels
  29122. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29123. Scene.LongPressDelay = 500; // in milliseconds
  29124. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29125. Scene.DoubleClickDelay = 300; // in milliseconds
  29126. /** If you need to check double click without raising a single click at first click, enable this flag */
  29127. Scene.ExclusiveDoubleClickMode = false;
  29128. return Scene;
  29129. }());
  29130. BABYLON.Scene = Scene;
  29131. })(BABYLON || (BABYLON = {}));
  29132. //# sourceMappingURL=babylon.scene.js.map
  29133. var BABYLON;
  29134. (function (BABYLON) {
  29135. /**
  29136. * Set of assets to keep when moving a scene into an asset container.
  29137. */
  29138. var KeepAssets = /** @class */ (function () {
  29139. function KeepAssets() {
  29140. /**
  29141. * Cameras to keep.
  29142. */
  29143. this.cameras = new Array();
  29144. /**
  29145. * Lights to keep.
  29146. */
  29147. this.lights = new Array();
  29148. /**
  29149. * Meshes to keep.
  29150. */
  29151. this.meshes = new Array();
  29152. /**
  29153. * Skeletons to keep.
  29154. */
  29155. this.skeletons = new Array();
  29156. /**
  29157. * ParticleSystems to keep.
  29158. */
  29159. this.particleSystems = new Array();
  29160. /**
  29161. * Animations to keep.
  29162. */
  29163. this.animations = new Array();
  29164. /**
  29165. * AnimationGroups to keep.
  29166. */
  29167. this.animationGroups = new Array();
  29168. /**
  29169. * MultiMaterials to keep.
  29170. */
  29171. this.multiMaterials = new Array();
  29172. /**
  29173. * Materials to keep.
  29174. */
  29175. this.materials = new Array();
  29176. /**
  29177. * MorphTargetManagers to keep.
  29178. */
  29179. this.morphTargetManagers = new Array();
  29180. /**
  29181. * Geometries to keep.
  29182. */
  29183. this.geometries = new Array();
  29184. /**
  29185. * TransformNodes to keep.
  29186. */
  29187. this.transformNodes = new Array();
  29188. /**
  29189. * LensFlareSystems to keep.
  29190. */
  29191. this.lensFlareSystems = new Array();
  29192. /**
  29193. * ShadowGenerators to keep.
  29194. */
  29195. this.shadowGenerators = new Array();
  29196. /**
  29197. * ActionManagers to keep.
  29198. */
  29199. this.actionManagers = new Array();
  29200. /**
  29201. * Sounds to keep.
  29202. */
  29203. this.sounds = new Array();
  29204. /**
  29205. * Textures to keep.
  29206. */
  29207. this.textures = new Array();
  29208. /**
  29209. * Effect layers to keep.
  29210. */
  29211. this.effectLayers = new Array();
  29212. }
  29213. return KeepAssets;
  29214. }());
  29215. BABYLON.KeepAssets = KeepAssets;
  29216. /**
  29217. * Container with a set of assets that can be added or removed from a scene.
  29218. */
  29219. var AssetContainer = /** @class */ (function () {
  29220. /**
  29221. * Instantiates an AssetContainer.
  29222. * @param scene The scene the AssetContainer belongs to.
  29223. */
  29224. function AssetContainer(scene) {
  29225. // Objects
  29226. /**
  29227. * Cameras populated in the container.
  29228. */
  29229. this.cameras = new Array();
  29230. /**
  29231. * Lights populated in the container.
  29232. */
  29233. this.lights = new Array();
  29234. /**
  29235. * Meshes populated in the container.
  29236. */
  29237. this.meshes = new Array();
  29238. /**
  29239. * Skeletons populated in the container.
  29240. */
  29241. this.skeletons = new Array();
  29242. /**
  29243. * ParticleSystems populated in the container.
  29244. */
  29245. this.particleSystems = new Array();
  29246. /**
  29247. * Animations populated in the container.
  29248. */
  29249. this.animations = new Array();
  29250. /**
  29251. * AnimationGroups populated in the container.
  29252. */
  29253. this.animationGroups = new Array();
  29254. /**
  29255. * MultiMaterials populated in the container.
  29256. */
  29257. this.multiMaterials = new Array();
  29258. /**
  29259. * Materials populated in the container.
  29260. */
  29261. this.materials = new Array();
  29262. /**
  29263. * MorphTargetManagers populated in the container.
  29264. */
  29265. this.morphTargetManagers = new Array();
  29266. /**
  29267. * Geometries populated in the container.
  29268. */
  29269. this.geometries = new Array();
  29270. /**
  29271. * TransformNodes populated in the container.
  29272. */
  29273. this.transformNodes = new Array();
  29274. /**
  29275. * LensFlareSystems populated in the container.
  29276. */
  29277. this.lensFlareSystems = new Array();
  29278. /**
  29279. * ShadowGenerators populated in the container.
  29280. */
  29281. this.shadowGenerators = new Array();
  29282. /**
  29283. * ActionManagers populated in the container.
  29284. */
  29285. this.actionManagers = new Array();
  29286. /**
  29287. * Sounds populated in the container.
  29288. */
  29289. this.sounds = new Array();
  29290. /**
  29291. * Textures populated in the container.
  29292. */
  29293. this.textures = new Array();
  29294. /**
  29295. * Effect layers populated in the container.
  29296. */
  29297. this.effectLayers = new Array();
  29298. this.scene = scene;
  29299. }
  29300. /**
  29301. * Adds all the assets from the container to the scene.
  29302. */
  29303. AssetContainer.prototype.addAllToScene = function () {
  29304. var _this = this;
  29305. this.cameras.forEach(function (o) {
  29306. _this.scene.addCamera(o);
  29307. });
  29308. this.lights.forEach(function (o) {
  29309. _this.scene.addLight(o);
  29310. });
  29311. this.meshes.forEach(function (o) {
  29312. _this.scene.addMesh(o);
  29313. });
  29314. this.skeletons.forEach(function (o) {
  29315. _this.scene.addSkeleton(o);
  29316. });
  29317. this.particleSystems.forEach(function (o) {
  29318. _this.scene.addParticleSystem(o);
  29319. });
  29320. this.animations.forEach(function (o) {
  29321. _this.scene.addAnimation(o);
  29322. });
  29323. this.animationGroups.forEach(function (o) {
  29324. _this.scene.addAnimationGroup(o);
  29325. });
  29326. this.multiMaterials.forEach(function (o) {
  29327. _this.scene.addMultiMaterial(o);
  29328. });
  29329. this.materials.forEach(function (o) {
  29330. _this.scene.addMaterial(o);
  29331. });
  29332. this.morphTargetManagers.forEach(function (o) {
  29333. _this.scene.addMorphTargetManager(o);
  29334. });
  29335. this.geometries.forEach(function (o) {
  29336. _this.scene.addGeometry(o);
  29337. });
  29338. this.transformNodes.forEach(function (o) {
  29339. _this.scene.addTransformNode(o);
  29340. });
  29341. this.lensFlareSystems.forEach(function (o) {
  29342. _this.scene.addLensFlareSystem(o);
  29343. });
  29344. this.actionManagers.forEach(function (o) {
  29345. _this.scene.addActionManager(o);
  29346. });
  29347. this.sounds.forEach(function (o) {
  29348. o.play();
  29349. o.autoplay = true;
  29350. _this.scene.mainSoundTrack.AddSound(o);
  29351. });
  29352. this.textures.forEach(function (o) {
  29353. _this.scene.addTexture(o);
  29354. });
  29355. this.effectLayers.forEach(function (o) {
  29356. _this.scene.addEffectLayer(o);
  29357. });
  29358. };
  29359. /**
  29360. * Removes all the assets in the container from the scene
  29361. */
  29362. AssetContainer.prototype.removeAllFromScene = function () {
  29363. var _this = this;
  29364. this.cameras.forEach(function (o) {
  29365. _this.scene.removeCamera(o);
  29366. });
  29367. this.lights.forEach(function (o) {
  29368. _this.scene.removeLight(o);
  29369. });
  29370. this.meshes.forEach(function (o) {
  29371. _this.scene.removeMesh(o);
  29372. });
  29373. this.skeletons.forEach(function (o) {
  29374. _this.scene.removeSkeleton(o);
  29375. });
  29376. this.particleSystems.forEach(function (o) {
  29377. _this.scene.removeParticleSystem(o);
  29378. });
  29379. this.animations.forEach(function (o) {
  29380. _this.scene.removeAnimation(o);
  29381. });
  29382. this.animationGroups.forEach(function (o) {
  29383. _this.scene.removeAnimationGroup(o);
  29384. });
  29385. this.multiMaterials.forEach(function (o) {
  29386. _this.scene.removeMultiMaterial(o);
  29387. });
  29388. this.materials.forEach(function (o) {
  29389. _this.scene.removeMaterial(o);
  29390. });
  29391. this.morphTargetManagers.forEach(function (o) {
  29392. _this.scene.removeMorphTargetManager(o);
  29393. });
  29394. this.geometries.forEach(function (o) {
  29395. _this.scene.removeGeometry(o);
  29396. });
  29397. this.transformNodes.forEach(function (o) {
  29398. _this.scene.removeTransformNode(o);
  29399. });
  29400. this.lensFlareSystems.forEach(function (o) {
  29401. _this.scene.removeLensFlareSystem(o);
  29402. });
  29403. this.actionManagers.forEach(function (o) {
  29404. _this.scene.removeActionManager(o);
  29405. });
  29406. this.sounds.forEach(function (o) {
  29407. o.stop();
  29408. o.autoplay = false;
  29409. _this.scene.mainSoundTrack.RemoveSound(o);
  29410. });
  29411. this.textures.forEach(function (o) {
  29412. _this.scene.removeTexture(o);
  29413. });
  29414. this.effectLayers.forEach(function (o) {
  29415. _this.scene.removeEffectLayer(o);
  29416. });
  29417. };
  29418. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29419. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29420. var asset = sourceAssets_1[_i];
  29421. var move = true;
  29422. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29423. var keepAsset = keepAssets_1[_a];
  29424. if (asset === keepAsset) {
  29425. move = false;
  29426. break;
  29427. }
  29428. }
  29429. if (move) {
  29430. targetAssets.push(asset);
  29431. }
  29432. }
  29433. };
  29434. /**
  29435. * Removes all the assets contained in the scene and adds them to the container.
  29436. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29437. */
  29438. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29439. if (keepAssets === undefined) {
  29440. keepAssets = new KeepAssets();
  29441. }
  29442. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29443. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29444. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29445. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29446. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29447. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29448. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29449. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29450. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29451. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29452. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29453. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29454. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29455. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29456. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29457. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29458. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29459. this.removeAllFromScene();
  29460. };
  29461. /**
  29462. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29463. * @returns the root mesh
  29464. */
  29465. AssetContainer.prototype.createRootMesh = function () {
  29466. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29467. this.meshes.forEach(function (m) {
  29468. if (!m.parent) {
  29469. rootMesh.addChild(m);
  29470. }
  29471. });
  29472. this.meshes.unshift(rootMesh);
  29473. return rootMesh;
  29474. };
  29475. return AssetContainer;
  29476. }());
  29477. BABYLON.AssetContainer = AssetContainer;
  29478. })(BABYLON || (BABYLON = {}));
  29479. //# sourceMappingURL=babylon.assetContainer.js.map
  29480. var BABYLON;
  29481. (function (BABYLON) {
  29482. var Buffer = /** @class */ (function () {
  29483. /**
  29484. * Constructor
  29485. * @param engine the engine
  29486. * @param data the data to use for this buffer
  29487. * @param updatable whether the data is updatable
  29488. * @param stride the stride (optional)
  29489. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29490. * @param instanced whether the buffer is instanced (optional)
  29491. * @param useBytes set to true if the stride in in bytes (optional)
  29492. */
  29493. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29494. if (stride === void 0) { stride = 0; }
  29495. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29496. if (instanced === void 0) { instanced = false; }
  29497. if (useBytes === void 0) { useBytes = false; }
  29498. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29499. this._engine = engine.getScene().getEngine();
  29500. }
  29501. else {
  29502. this._engine = engine;
  29503. }
  29504. this._updatable = updatable;
  29505. this._instanced = instanced;
  29506. this._data = data;
  29507. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29508. if (!postponeInternalCreation) { // by default
  29509. this.create();
  29510. }
  29511. }
  29512. /**
  29513. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29514. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29515. * @param offset defines offset in the buffer (0 by default)
  29516. * @param size defines the size in floats of attributes (position is 3 for instance)
  29517. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29518. * @param instanced defines if the vertex buffer contains indexed data
  29519. * @param useBytes defines if the offset and stride are in bytes
  29520. * @returns the new vertex buffer
  29521. */
  29522. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29523. if (useBytes === void 0) { useBytes = false; }
  29524. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29525. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29526. // a lot of these parameters are ignored as they are overriden by the buffer
  29527. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29528. };
  29529. // Properties
  29530. Buffer.prototype.isUpdatable = function () {
  29531. return this._updatable;
  29532. };
  29533. Buffer.prototype.getData = function () {
  29534. return this._data;
  29535. };
  29536. Buffer.prototype.getBuffer = function () {
  29537. return this._buffer;
  29538. };
  29539. /**
  29540. * Gets the stride in float32 units (i.e. byte stride / 4).
  29541. * May not be an integer if the byte stride is not divisible by 4.
  29542. * DEPRECATED. Use byteStride instead.
  29543. * @returns the stride in float32 units
  29544. */
  29545. Buffer.prototype.getStrideSize = function () {
  29546. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29547. };
  29548. // Methods
  29549. Buffer.prototype.create = function (data) {
  29550. if (data === void 0) { data = null; }
  29551. if (!data && this._buffer) {
  29552. return; // nothing to do
  29553. }
  29554. data = data || this._data;
  29555. if (!data) {
  29556. return;
  29557. }
  29558. if (!this._buffer) { // create buffer
  29559. if (this._updatable) {
  29560. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29561. this._data = data;
  29562. }
  29563. else {
  29564. this._buffer = this._engine.createVertexBuffer(data);
  29565. }
  29566. }
  29567. else if (this._updatable) { // update buffer
  29568. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29569. this._data = data;
  29570. }
  29571. };
  29572. Buffer.prototype._rebuild = function () {
  29573. this._buffer = null;
  29574. this.create(this._data);
  29575. };
  29576. Buffer.prototype.update = function (data) {
  29577. this.create(data);
  29578. };
  29579. /**
  29580. * Updates the data directly.
  29581. * @param data the new data
  29582. * @param offset the new offset
  29583. * @param vertexCount the vertex count (optional)
  29584. * @param useBytes set to true if the offset is in bytes
  29585. */
  29586. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29587. if (useBytes === void 0) { useBytes = false; }
  29588. if (!this._buffer) {
  29589. return;
  29590. }
  29591. if (this._updatable) { // update buffer
  29592. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29593. this._data = null;
  29594. }
  29595. };
  29596. Buffer.prototype.dispose = function () {
  29597. if (!this._buffer) {
  29598. return;
  29599. }
  29600. if (this._engine._releaseBuffer(this._buffer)) {
  29601. this._buffer = null;
  29602. }
  29603. };
  29604. return Buffer;
  29605. }());
  29606. BABYLON.Buffer = Buffer;
  29607. })(BABYLON || (BABYLON = {}));
  29608. //# sourceMappingURL=babylon.buffer.js.map
  29609. var BABYLON;
  29610. (function (BABYLON) {
  29611. var VertexBuffer = /** @class */ (function () {
  29612. /**
  29613. * Constructor
  29614. * @param engine the engine
  29615. * @param data the data to use for this vertex buffer
  29616. * @param kind the vertex buffer kind
  29617. * @param updatable whether the data is updatable
  29618. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29619. * @param stride the stride (optional)
  29620. * @param instanced whether the buffer is instanced (optional)
  29621. * @param offset the offset of the data (optional)
  29622. * @param size the number of components (optional)
  29623. * @param type the type of the component (optional)
  29624. * @param normalized whether the data contains normalized data (optional)
  29625. * @param useBytes set to true if stride and offset are in bytes (optional)
  29626. */
  29627. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29628. if (normalized === void 0) { normalized = false; }
  29629. if (useBytes === void 0) { useBytes = false; }
  29630. if (data instanceof BABYLON.Buffer) {
  29631. this._buffer = data;
  29632. this._ownsBuffer = false;
  29633. }
  29634. else {
  29635. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29636. this._ownsBuffer = true;
  29637. }
  29638. this._kind = kind;
  29639. if (type == undefined) {
  29640. var data_1 = this.getData();
  29641. this.type = VertexBuffer.FLOAT;
  29642. if (data_1 instanceof Int8Array)
  29643. this.type = VertexBuffer.BYTE;
  29644. else if (data_1 instanceof Uint8Array)
  29645. this.type = VertexBuffer.UNSIGNED_BYTE;
  29646. else if (data_1 instanceof Int16Array)
  29647. this.type = VertexBuffer.SHORT;
  29648. else if (data_1 instanceof Uint16Array)
  29649. this.type = VertexBuffer.UNSIGNED_SHORT;
  29650. else if (data_1 instanceof Int32Array)
  29651. this.type = VertexBuffer.INT;
  29652. else if (data_1 instanceof Uint32Array)
  29653. this.type = VertexBuffer.UNSIGNED_INT;
  29654. }
  29655. else {
  29656. this.type = type;
  29657. }
  29658. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29659. if (useBytes) {
  29660. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29661. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29662. this.byteOffset = offset || 0;
  29663. }
  29664. else {
  29665. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29666. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29667. this.byteOffset = (offset || 0) * typeByteLength;
  29668. }
  29669. this.normalized = normalized;
  29670. this._instanced = instanced !== undefined ? instanced : false;
  29671. this._instanceDivisor = instanced ? 1 : 0;
  29672. }
  29673. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29674. /**
  29675. * Gets or sets the instance divisor when in instanced mode
  29676. */
  29677. get: function () {
  29678. return this._instanceDivisor;
  29679. },
  29680. set: function (value) {
  29681. this._instanceDivisor = value;
  29682. if (value == 0) {
  29683. this._instanced = false;
  29684. }
  29685. else {
  29686. this._instanced = true;
  29687. }
  29688. },
  29689. enumerable: true,
  29690. configurable: true
  29691. });
  29692. VertexBuffer.prototype._rebuild = function () {
  29693. if (!this._buffer) {
  29694. return;
  29695. }
  29696. this._buffer._rebuild();
  29697. };
  29698. /**
  29699. * Returns the kind of the VertexBuffer (string).
  29700. */
  29701. VertexBuffer.prototype.getKind = function () {
  29702. return this._kind;
  29703. };
  29704. // Properties
  29705. /**
  29706. * Boolean : is the VertexBuffer updatable ?
  29707. */
  29708. VertexBuffer.prototype.isUpdatable = function () {
  29709. return this._buffer.isUpdatable();
  29710. };
  29711. /**
  29712. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29713. */
  29714. VertexBuffer.prototype.getData = function () {
  29715. return this._buffer.getData();
  29716. };
  29717. /**
  29718. * Returns the WebGLBuffer associated to the VertexBuffer.
  29719. */
  29720. VertexBuffer.prototype.getBuffer = function () {
  29721. return this._buffer.getBuffer();
  29722. };
  29723. /**
  29724. * Returns the stride as a multiple of the type byte length.
  29725. * DEPRECATED. Use byteStride instead.
  29726. */
  29727. VertexBuffer.prototype.getStrideSize = function () {
  29728. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29729. };
  29730. /**
  29731. * Returns the offset as a multiple of the type byte length.
  29732. * DEPRECATED. Use byteOffset instead.
  29733. */
  29734. VertexBuffer.prototype.getOffset = function () {
  29735. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29736. };
  29737. /**
  29738. * Returns the number of components per vertex attribute (integer).
  29739. */
  29740. VertexBuffer.prototype.getSize = function () {
  29741. return this._size;
  29742. };
  29743. /**
  29744. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29745. */
  29746. VertexBuffer.prototype.getIsInstanced = function () {
  29747. return this._instanced;
  29748. };
  29749. /**
  29750. * Returns the instancing divisor, zero for non-instanced (integer).
  29751. */
  29752. VertexBuffer.prototype.getInstanceDivisor = function () {
  29753. return this._instanceDivisor;
  29754. };
  29755. // Methods
  29756. /**
  29757. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29758. * Returns the created WebGLBuffer.
  29759. */
  29760. VertexBuffer.prototype.create = function (data) {
  29761. return this._buffer.create(data);
  29762. };
  29763. /**
  29764. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29765. * This function will create a new buffer if the current one is not updatable
  29766. * Returns the updated WebGLBuffer.
  29767. */
  29768. VertexBuffer.prototype.update = function (data) {
  29769. return this._buffer.update(data);
  29770. };
  29771. /**
  29772. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29773. * Returns the directly updated WebGLBuffer.
  29774. * @param data the new data
  29775. * @param offset the new offset
  29776. * @param useBytes set to true if the offset is in bytes
  29777. */
  29778. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29779. if (useBytes === void 0) { useBytes = false; }
  29780. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29781. };
  29782. /**
  29783. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29784. */
  29785. VertexBuffer.prototype.dispose = function () {
  29786. if (this._ownsBuffer) {
  29787. this._buffer.dispose();
  29788. }
  29789. };
  29790. /**
  29791. * Enumerates each value of this vertex buffer as numbers.
  29792. * @param count the number of values to enumerate
  29793. * @param callback the callback function called for each value
  29794. */
  29795. VertexBuffer.prototype.forEach = function (count, callback) {
  29796. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29797. };
  29798. Object.defineProperty(VertexBuffer, "PositionKind", {
  29799. get: function () {
  29800. return VertexBuffer._PositionKind;
  29801. },
  29802. enumerable: true,
  29803. configurable: true
  29804. });
  29805. Object.defineProperty(VertexBuffer, "NormalKind", {
  29806. get: function () {
  29807. return VertexBuffer._NormalKind;
  29808. },
  29809. enumerable: true,
  29810. configurable: true
  29811. });
  29812. Object.defineProperty(VertexBuffer, "TangentKind", {
  29813. get: function () {
  29814. return VertexBuffer._TangentKind;
  29815. },
  29816. enumerable: true,
  29817. configurable: true
  29818. });
  29819. Object.defineProperty(VertexBuffer, "UVKind", {
  29820. get: function () {
  29821. return VertexBuffer._UVKind;
  29822. },
  29823. enumerable: true,
  29824. configurable: true
  29825. });
  29826. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29827. get: function () {
  29828. return VertexBuffer._UV2Kind;
  29829. },
  29830. enumerable: true,
  29831. configurable: true
  29832. });
  29833. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29834. get: function () {
  29835. return VertexBuffer._UV3Kind;
  29836. },
  29837. enumerable: true,
  29838. configurable: true
  29839. });
  29840. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29841. get: function () {
  29842. return VertexBuffer._UV4Kind;
  29843. },
  29844. enumerable: true,
  29845. configurable: true
  29846. });
  29847. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29848. get: function () {
  29849. return VertexBuffer._UV5Kind;
  29850. },
  29851. enumerable: true,
  29852. configurable: true
  29853. });
  29854. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29855. get: function () {
  29856. return VertexBuffer._UV6Kind;
  29857. },
  29858. enumerable: true,
  29859. configurable: true
  29860. });
  29861. Object.defineProperty(VertexBuffer, "ColorKind", {
  29862. get: function () {
  29863. return VertexBuffer._ColorKind;
  29864. },
  29865. enumerable: true,
  29866. configurable: true
  29867. });
  29868. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29869. get: function () {
  29870. return VertexBuffer._MatricesIndicesKind;
  29871. },
  29872. enumerable: true,
  29873. configurable: true
  29874. });
  29875. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29876. get: function () {
  29877. return VertexBuffer._MatricesWeightsKind;
  29878. },
  29879. enumerable: true,
  29880. configurable: true
  29881. });
  29882. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29883. get: function () {
  29884. return VertexBuffer._MatricesIndicesExtraKind;
  29885. },
  29886. enumerable: true,
  29887. configurable: true
  29888. });
  29889. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29890. get: function () {
  29891. return VertexBuffer._MatricesWeightsExtraKind;
  29892. },
  29893. enumerable: true,
  29894. configurable: true
  29895. });
  29896. /**
  29897. * Deduces the stride given a kind.
  29898. * @param kind The kind string to deduce
  29899. * @returns The deduced stride
  29900. */
  29901. VertexBuffer.DeduceStride = function (kind) {
  29902. switch (kind) {
  29903. case VertexBuffer.UVKind:
  29904. case VertexBuffer.UV2Kind:
  29905. case VertexBuffer.UV3Kind:
  29906. case VertexBuffer.UV4Kind:
  29907. case VertexBuffer.UV5Kind:
  29908. case VertexBuffer.UV6Kind:
  29909. return 2;
  29910. case VertexBuffer.NormalKind:
  29911. case VertexBuffer.PositionKind:
  29912. return 3;
  29913. case VertexBuffer.ColorKind:
  29914. case VertexBuffer.MatricesIndicesKind:
  29915. case VertexBuffer.MatricesIndicesExtraKind:
  29916. case VertexBuffer.MatricesWeightsKind:
  29917. case VertexBuffer.MatricesWeightsExtraKind:
  29918. case VertexBuffer.TangentKind:
  29919. return 4;
  29920. default:
  29921. throw new Error("Invalid kind '" + kind + "'");
  29922. }
  29923. };
  29924. /**
  29925. * Gets the byte length of the given type.
  29926. * @param type the type
  29927. * @returns the number of bytes
  29928. */
  29929. VertexBuffer.GetTypeByteLength = function (type) {
  29930. switch (type) {
  29931. case VertexBuffer.BYTE:
  29932. case VertexBuffer.UNSIGNED_BYTE:
  29933. return 1;
  29934. case VertexBuffer.SHORT:
  29935. case VertexBuffer.UNSIGNED_SHORT:
  29936. return 2;
  29937. case VertexBuffer.INT:
  29938. case VertexBuffer.FLOAT:
  29939. return 4;
  29940. default:
  29941. throw new Error("Invalid type '" + type + "'");
  29942. }
  29943. };
  29944. /**
  29945. * Enumerates each value of the given parameters as numbers.
  29946. * @param data the data to enumerate
  29947. * @param byteOffset the byte offset of the data
  29948. * @param byteStride the byte stride of the data
  29949. * @param componentCount the number of components per element
  29950. * @param componentType the type of the component
  29951. * @param count the total number of components
  29952. * @param normalized whether the data is normalized
  29953. * @param callback the callback function called for each value
  29954. */
  29955. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29956. if (data instanceof Array) {
  29957. var offset = byteOffset / 4;
  29958. var stride = byteStride / 4;
  29959. for (var index = 0; index < count; index += componentCount) {
  29960. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29961. callback(data[offset + componentIndex], index + componentIndex);
  29962. }
  29963. offset += stride;
  29964. }
  29965. }
  29966. else {
  29967. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29968. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29969. for (var index = 0; index < count; index += componentCount) {
  29970. var componentByteOffset = byteOffset;
  29971. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29972. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29973. callback(value, index + componentIndex);
  29974. componentByteOffset += componentByteLength;
  29975. }
  29976. byteOffset += byteStride;
  29977. }
  29978. }
  29979. };
  29980. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29981. switch (type) {
  29982. case VertexBuffer.BYTE: {
  29983. var value = dataView.getInt8(byteOffset);
  29984. if (normalized) {
  29985. value = Math.max(value / 127, -1);
  29986. }
  29987. return value;
  29988. }
  29989. case VertexBuffer.UNSIGNED_BYTE: {
  29990. var value = dataView.getUint8(byteOffset);
  29991. if (normalized) {
  29992. value = value / 255;
  29993. }
  29994. return value;
  29995. }
  29996. case VertexBuffer.SHORT: {
  29997. var value = dataView.getInt16(byteOffset, true);
  29998. if (normalized) {
  29999. value = Math.max(value / 16383, -1);
  30000. }
  30001. return value;
  30002. }
  30003. case VertexBuffer.UNSIGNED_SHORT: {
  30004. var value = dataView.getUint16(byteOffset, true);
  30005. if (normalized) {
  30006. value = value / 65535;
  30007. }
  30008. return value;
  30009. }
  30010. case VertexBuffer.FLOAT: {
  30011. return dataView.getFloat32(byteOffset, true);
  30012. }
  30013. default: {
  30014. throw new Error("Invalid component type " + type);
  30015. }
  30016. }
  30017. };
  30018. /**
  30019. * The byte type.
  30020. */
  30021. VertexBuffer.BYTE = 5120;
  30022. /**
  30023. * The unsigned byte type.
  30024. */
  30025. VertexBuffer.UNSIGNED_BYTE = 5121;
  30026. /**
  30027. * The short type.
  30028. */
  30029. VertexBuffer.SHORT = 5122;
  30030. /**
  30031. * The unsigned short type.
  30032. */
  30033. VertexBuffer.UNSIGNED_SHORT = 5123;
  30034. /**
  30035. * The integer type.
  30036. */
  30037. VertexBuffer.INT = 5124;
  30038. /**
  30039. * The unsigned integer type.
  30040. */
  30041. VertexBuffer.UNSIGNED_INT = 5125;
  30042. /**
  30043. * The float type.
  30044. */
  30045. VertexBuffer.FLOAT = 5126;
  30046. // Enums
  30047. VertexBuffer._PositionKind = "position";
  30048. VertexBuffer._NormalKind = "normal";
  30049. VertexBuffer._TangentKind = "tangent";
  30050. VertexBuffer._UVKind = "uv";
  30051. VertexBuffer._UV2Kind = "uv2";
  30052. VertexBuffer._UV3Kind = "uv3";
  30053. VertexBuffer._UV4Kind = "uv4";
  30054. VertexBuffer._UV5Kind = "uv5";
  30055. VertexBuffer._UV6Kind = "uv6";
  30056. VertexBuffer._ColorKind = "color";
  30057. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30058. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30059. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30060. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30061. return VertexBuffer;
  30062. }());
  30063. BABYLON.VertexBuffer = VertexBuffer;
  30064. })(BABYLON || (BABYLON = {}));
  30065. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30066. var BABYLON;
  30067. (function (BABYLON) {
  30068. /**
  30069. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30070. */
  30071. var DummyInternalTextureTracker = /** @class */ (function () {
  30072. function DummyInternalTextureTracker() {
  30073. /**
  30074. * Gets or set the previous tracker in the list
  30075. */
  30076. this.previous = null;
  30077. /**
  30078. * Gets or set the next tracker in the list
  30079. */
  30080. this.next = null;
  30081. }
  30082. return DummyInternalTextureTracker;
  30083. }());
  30084. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30085. })(BABYLON || (BABYLON = {}));
  30086. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30087. var BABYLON;
  30088. (function (BABYLON) {
  30089. /**
  30090. * Class used to store data associated with WebGL texture data for the engine
  30091. * This class should not be used directly
  30092. */
  30093. var InternalTexture = /** @class */ (function () {
  30094. /**
  30095. * Creates a new InternalTexture
  30096. * @param engine defines the engine to use
  30097. * @param dataSource defines the type of data that will be used
  30098. */
  30099. function InternalTexture(engine, dataSource) {
  30100. /**
  30101. * Observable called when the texture is loaded
  30102. */
  30103. this.onLoadedObservable = new BABYLON.Observable();
  30104. /**
  30105. * Gets or set the previous tracker in the list
  30106. */
  30107. this.previous = null;
  30108. /**
  30109. * Gets or set the next tracker in the list
  30110. */
  30111. this.next = null;
  30112. // Private
  30113. /** @hidden */
  30114. this._initialSlot = -1;
  30115. /** @hidden */
  30116. this._designatedSlot = -1;
  30117. /** @hidden */
  30118. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30119. /** @hidden */
  30120. this._comparisonFunction = 0;
  30121. /** @hidden */
  30122. this._isRGBD = false;
  30123. /** @hidden */
  30124. this._references = 1;
  30125. this._engine = engine;
  30126. this._dataSource = dataSource;
  30127. this._webGLTexture = engine._createTexture();
  30128. }
  30129. /**
  30130. * Gets the Engine the texture belongs to.
  30131. * @returns The babylon engine
  30132. */
  30133. InternalTexture.prototype.getEngine = function () {
  30134. return this._engine;
  30135. };
  30136. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30137. /**
  30138. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30139. */
  30140. get: function () {
  30141. return this._dataSource;
  30142. },
  30143. enumerable: true,
  30144. configurable: true
  30145. });
  30146. /**
  30147. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30148. */
  30149. InternalTexture.prototype.incrementReferences = function () {
  30150. this._references++;
  30151. };
  30152. /**
  30153. * Change the size of the texture (not the size of the content)
  30154. * @param width defines the new width
  30155. * @param height defines the new height
  30156. * @param depth defines the new depth (1 by default)
  30157. */
  30158. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30159. if (depth === void 0) { depth = 1; }
  30160. this.width = width;
  30161. this.height = height;
  30162. this.depth = depth;
  30163. this.baseWidth = width;
  30164. this.baseHeight = height;
  30165. this.baseDepth = depth;
  30166. this._size = width * height * depth;
  30167. };
  30168. /** @hidden */
  30169. InternalTexture.prototype._rebuild = function () {
  30170. var _this = this;
  30171. var proxy;
  30172. this.isReady = false;
  30173. this._cachedCoordinatesMode = null;
  30174. this._cachedWrapU = null;
  30175. this._cachedWrapV = null;
  30176. this._cachedAnisotropicFilteringLevel = null;
  30177. switch (this._dataSource) {
  30178. case InternalTexture.DATASOURCE_TEMP:
  30179. return;
  30180. case InternalTexture.DATASOURCE_URL:
  30181. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30182. _this.isReady = true;
  30183. }, null, this._buffer, undefined, this.format);
  30184. proxy._swapAndDie(this);
  30185. return;
  30186. case InternalTexture.DATASOURCE_RAW:
  30187. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30188. proxy._swapAndDie(this);
  30189. this.isReady = true;
  30190. return;
  30191. case InternalTexture.DATASOURCE_RAW3D:
  30192. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30193. proxy._swapAndDie(this);
  30194. this.isReady = true;
  30195. return;
  30196. case InternalTexture.DATASOURCE_DYNAMIC:
  30197. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30198. proxy._swapAndDie(this);
  30199. // The engine will make sure to update content so no need to flag it as isReady = true
  30200. return;
  30201. case InternalTexture.DATASOURCE_RENDERTARGET:
  30202. var options = new BABYLON.RenderTargetCreationOptions();
  30203. options.generateDepthBuffer = this._generateDepthBuffer;
  30204. options.generateMipMaps = this.generateMipMaps;
  30205. options.generateStencilBuffer = this._generateStencilBuffer;
  30206. options.samplingMode = this.samplingMode;
  30207. options.type = this.type;
  30208. if (this.isCube) {
  30209. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30210. }
  30211. else {
  30212. var size = {
  30213. width: this.width,
  30214. height: this.height
  30215. };
  30216. proxy = this._engine.createRenderTargetTexture(size, options);
  30217. }
  30218. proxy._swapAndDie(this);
  30219. this.isReady = true;
  30220. return;
  30221. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30222. var depthTextureOptions = {
  30223. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30224. comparisonFunction: this._comparisonFunction,
  30225. generateStencil: this._generateStencilBuffer,
  30226. isCube: this.isCube
  30227. };
  30228. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30229. proxy._swapAndDie(this);
  30230. this.isReady = true;
  30231. return;
  30232. case InternalTexture.DATASOURCE_CUBE:
  30233. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30234. _this.isReady = true;
  30235. }, null, this.format, this._extension);
  30236. proxy._swapAndDie(this);
  30237. return;
  30238. case InternalTexture.DATASOURCE_CUBERAW:
  30239. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30240. proxy._swapAndDie(this);
  30241. this.isReady = true;
  30242. return;
  30243. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30244. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30245. if (proxy) {
  30246. proxy._swapAndDie(_this);
  30247. }
  30248. _this.isReady = true;
  30249. }, null, this.format, this._extension);
  30250. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30251. return;
  30252. }
  30253. };
  30254. InternalTexture.prototype._swapAndDie = function (target) {
  30255. target._webGLTexture = this._webGLTexture;
  30256. if (this._framebuffer) {
  30257. target._framebuffer = this._framebuffer;
  30258. }
  30259. if (this._depthStencilBuffer) {
  30260. target._depthStencilBuffer = this._depthStencilBuffer;
  30261. }
  30262. if (this._lodTextureHigh) {
  30263. if (target._lodTextureHigh) {
  30264. target._lodTextureHigh.dispose();
  30265. }
  30266. target._lodTextureHigh = this._lodTextureHigh;
  30267. }
  30268. if (this._lodTextureMid) {
  30269. if (target._lodTextureMid) {
  30270. target._lodTextureMid.dispose();
  30271. }
  30272. target._lodTextureMid = this._lodTextureMid;
  30273. }
  30274. if (this._lodTextureLow) {
  30275. if (target._lodTextureLow) {
  30276. target._lodTextureLow.dispose();
  30277. }
  30278. target._lodTextureLow = this._lodTextureLow;
  30279. }
  30280. var cache = this._engine.getLoadedTexturesCache();
  30281. var index = cache.indexOf(this);
  30282. if (index !== -1) {
  30283. cache.splice(index, 1);
  30284. }
  30285. };
  30286. /**
  30287. * Dispose the current allocated resources
  30288. */
  30289. InternalTexture.prototype.dispose = function () {
  30290. if (!this._webGLTexture) {
  30291. return;
  30292. }
  30293. this._references--;
  30294. if (this._references === 0) {
  30295. this._engine._releaseTexture(this);
  30296. this._webGLTexture = null;
  30297. this.previous = null;
  30298. this.next = null;
  30299. }
  30300. };
  30301. /**
  30302. * The source of the texture data is unknown
  30303. */
  30304. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30305. /**
  30306. * Texture data comes from an URL
  30307. */
  30308. InternalTexture.DATASOURCE_URL = 1;
  30309. /**
  30310. * Texture data is only used for temporary storage
  30311. */
  30312. InternalTexture.DATASOURCE_TEMP = 2;
  30313. /**
  30314. * Texture data comes from raw data (ArrayBuffer)
  30315. */
  30316. InternalTexture.DATASOURCE_RAW = 3;
  30317. /**
  30318. * Texture content is dynamic (video or dynamic texture)
  30319. */
  30320. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30321. /**
  30322. * Texture content is generated by rendering to it
  30323. */
  30324. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30325. /**
  30326. * Texture content is part of a multi render target process
  30327. */
  30328. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30329. /**
  30330. * Texture data comes from a cube data file
  30331. */
  30332. InternalTexture.DATASOURCE_CUBE = 7;
  30333. /**
  30334. * Texture data comes from a raw cube data
  30335. */
  30336. InternalTexture.DATASOURCE_CUBERAW = 8;
  30337. /**
  30338. * Texture data come from a prefiltered cube data file
  30339. */
  30340. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30341. /**
  30342. * Texture content is raw 3D data
  30343. */
  30344. InternalTexture.DATASOURCE_RAW3D = 10;
  30345. /**
  30346. * Texture content is a depth texture
  30347. */
  30348. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30349. return InternalTexture;
  30350. }());
  30351. BABYLON.InternalTexture = InternalTexture;
  30352. })(BABYLON || (BABYLON = {}));
  30353. //# sourceMappingURL=babylon.internalTexture.js.map
  30354. var BABYLON;
  30355. (function (BABYLON) {
  30356. var BaseTexture = /** @class */ (function () {
  30357. function BaseTexture(scene) {
  30358. this._hasAlpha = false;
  30359. this.getAlphaFromRGB = false;
  30360. this.level = 1;
  30361. this.coordinatesIndex = 0;
  30362. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30363. /**
  30364. * | Value | Type | Description |
  30365. * | ----- | ------------------ | ----------- |
  30366. * | 0 | CLAMP_ADDRESSMODE | |
  30367. * | 1 | WRAP_ADDRESSMODE | |
  30368. * | 2 | MIRROR_ADDRESSMODE | |
  30369. */
  30370. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30371. /**
  30372. * | Value | Type | Description |
  30373. * | ----- | ------------------ | ----------- |
  30374. * | 0 | CLAMP_ADDRESSMODE | |
  30375. * | 1 | WRAP_ADDRESSMODE | |
  30376. * | 2 | MIRROR_ADDRESSMODE | |
  30377. */
  30378. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30379. /**
  30380. * | Value | Type | Description |
  30381. * | ----- | ------------------ | ----------- |
  30382. * | 0 | CLAMP_ADDRESSMODE | |
  30383. * | 1 | WRAP_ADDRESSMODE | |
  30384. * | 2 | MIRROR_ADDRESSMODE | |
  30385. */
  30386. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30387. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30388. this.isCube = false;
  30389. this.is3D = false;
  30390. this.gammaSpace = true;
  30391. this.invertZ = false;
  30392. this.lodLevelInAlpha = false;
  30393. this.isRenderTarget = false;
  30394. this.animations = new Array();
  30395. /**
  30396. * An event triggered when the texture is disposed.
  30397. */
  30398. this.onDisposeObservable = new BABYLON.Observable();
  30399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30400. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30401. if (this._scene) {
  30402. this._scene.textures.push(this);
  30403. }
  30404. this._uid = null;
  30405. }
  30406. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30407. get: function () {
  30408. return this._hasAlpha;
  30409. },
  30410. set: function (value) {
  30411. if (this._hasAlpha === value) {
  30412. return;
  30413. }
  30414. this._hasAlpha = value;
  30415. if (this._scene) {
  30416. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30417. }
  30418. },
  30419. enumerable: true,
  30420. configurable: true
  30421. });
  30422. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30423. get: function () {
  30424. return this._coordinatesMode;
  30425. },
  30426. /**
  30427. * How a texture is mapped.
  30428. *
  30429. * | Value | Type | Description |
  30430. * | ----- | ----------------------------------- | ----------- |
  30431. * | 0 | EXPLICIT_MODE | |
  30432. * | 1 | SPHERICAL_MODE | |
  30433. * | 2 | PLANAR_MODE | |
  30434. * | 3 | CUBIC_MODE | |
  30435. * | 4 | PROJECTION_MODE | |
  30436. * | 5 | SKYBOX_MODE | |
  30437. * | 6 | INVCUBIC_MODE | |
  30438. * | 7 | EQUIRECTANGULAR_MODE | |
  30439. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30440. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30441. */
  30442. set: function (value) {
  30443. if (this._coordinatesMode === value) {
  30444. return;
  30445. }
  30446. this._coordinatesMode = value;
  30447. if (this._scene) {
  30448. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30449. }
  30450. },
  30451. enumerable: true,
  30452. configurable: true
  30453. });
  30454. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30455. /**
  30456. * Gets whether or not the texture contains RGBD data.
  30457. */
  30458. get: function () {
  30459. return this._texture != null && this._texture._isRGBD;
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30465. get: function () {
  30466. if (this._texture)
  30467. return this._texture._lodGenerationOffset;
  30468. return 0.0;
  30469. },
  30470. set: function (value) {
  30471. if (this._texture)
  30472. this._texture._lodGenerationOffset = value;
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30478. get: function () {
  30479. if (this._texture)
  30480. return this._texture._lodGenerationScale;
  30481. return 0.0;
  30482. },
  30483. set: function (value) {
  30484. if (this._texture)
  30485. this._texture._lodGenerationScale = value;
  30486. },
  30487. enumerable: true,
  30488. configurable: true
  30489. });
  30490. Object.defineProperty(BaseTexture.prototype, "uid", {
  30491. get: function () {
  30492. if (!this._uid) {
  30493. this._uid = BABYLON.Tools.RandomId();
  30494. }
  30495. return this._uid;
  30496. },
  30497. enumerable: true,
  30498. configurable: true
  30499. });
  30500. BaseTexture.prototype.toString = function () {
  30501. return this.name;
  30502. };
  30503. BaseTexture.prototype.getClassName = function () {
  30504. return "BaseTexture";
  30505. };
  30506. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30507. set: function (callback) {
  30508. if (this._onDisposeObserver) {
  30509. this.onDisposeObservable.remove(this._onDisposeObserver);
  30510. }
  30511. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30512. },
  30513. enumerable: true,
  30514. configurable: true
  30515. });
  30516. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30517. get: function () {
  30518. return true;
  30519. },
  30520. enumerable: true,
  30521. configurable: true
  30522. });
  30523. BaseTexture.prototype.getScene = function () {
  30524. return this._scene;
  30525. };
  30526. BaseTexture.prototype.getTextureMatrix = function () {
  30527. return BABYLON.Matrix.IdentityReadOnly;
  30528. };
  30529. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30530. return BABYLON.Matrix.IdentityReadOnly;
  30531. };
  30532. BaseTexture.prototype.getInternalTexture = function () {
  30533. return this._texture;
  30534. };
  30535. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30536. return !this.isBlocking || this.isReady();
  30537. };
  30538. BaseTexture.prototype.isReady = function () {
  30539. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30540. this.delayLoad();
  30541. return false;
  30542. }
  30543. if (this._texture) {
  30544. return this._texture.isReady;
  30545. }
  30546. return false;
  30547. };
  30548. BaseTexture.prototype.getSize = function () {
  30549. if (this._texture && this._texture.width) {
  30550. return new BABYLON.Size(this._texture.width, this._texture.height);
  30551. }
  30552. if (this._texture && this._texture._size) {
  30553. return new BABYLON.Size(this._texture._size, this._texture._size);
  30554. }
  30555. return BABYLON.Size.Zero();
  30556. };
  30557. BaseTexture.prototype.getBaseSize = function () {
  30558. if (!this.isReady() || !this._texture)
  30559. return BABYLON.Size.Zero();
  30560. if (this._texture._size) {
  30561. return new BABYLON.Size(this._texture._size, this._texture._size);
  30562. }
  30563. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30564. };
  30565. BaseTexture.prototype.scale = function (ratio) {
  30566. };
  30567. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30568. get: function () {
  30569. return false;
  30570. },
  30571. enumerable: true,
  30572. configurable: true
  30573. });
  30574. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30575. if (!this._scene) {
  30576. return null;
  30577. }
  30578. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30579. for (var index = 0; index < texturesCache.length; index++) {
  30580. var texturesCacheEntry = texturesCache[index];
  30581. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30582. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30583. texturesCacheEntry.incrementReferences();
  30584. return texturesCacheEntry;
  30585. }
  30586. }
  30587. }
  30588. return null;
  30589. };
  30590. BaseTexture.prototype._rebuild = function () {
  30591. };
  30592. BaseTexture.prototype.delayLoad = function () {
  30593. };
  30594. BaseTexture.prototype.clone = function () {
  30595. return null;
  30596. };
  30597. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30598. get: function () {
  30599. if (!this._texture) {
  30600. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30601. }
  30602. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30603. },
  30604. enumerable: true,
  30605. configurable: true
  30606. });
  30607. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30608. get: function () {
  30609. if (!this._texture) {
  30610. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30611. }
  30612. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30613. },
  30614. enumerable: true,
  30615. configurable: true
  30616. });
  30617. /**
  30618. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30619. * This will returns an RGBA array buffer containing either in values (0-255) or
  30620. * float values (0-1) depending of the underlying buffer type.
  30621. * @param faceIndex The face of the texture to read (in case of cube texture)
  30622. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30623. * @returns The Array buffer containing the pixels data.
  30624. */
  30625. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30626. if (faceIndex === void 0) { faceIndex = 0; }
  30627. if (level === void 0) { level = 0; }
  30628. if (!this._texture) {
  30629. return null;
  30630. }
  30631. var size = this.getSize();
  30632. var width = size.width;
  30633. var height = size.height;
  30634. var scene = this.getScene();
  30635. if (!scene) {
  30636. return null;
  30637. }
  30638. var engine = scene.getEngine();
  30639. if (level != 0) {
  30640. width = width / Math.pow(2, level);
  30641. height = height / Math.pow(2, level);
  30642. width = Math.round(width);
  30643. height = Math.round(height);
  30644. }
  30645. if (this._texture.isCube) {
  30646. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30647. }
  30648. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30649. };
  30650. BaseTexture.prototype.releaseInternalTexture = function () {
  30651. if (this._texture) {
  30652. this._texture.dispose();
  30653. this._texture = null;
  30654. }
  30655. };
  30656. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30657. get: function () {
  30658. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30659. return null;
  30660. }
  30661. if (!this._texture._sphericalPolynomial) {
  30662. this._texture._sphericalPolynomial =
  30663. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30664. }
  30665. return this._texture._sphericalPolynomial;
  30666. },
  30667. set: function (value) {
  30668. if (this._texture) {
  30669. this._texture._sphericalPolynomial = value;
  30670. }
  30671. },
  30672. enumerable: true,
  30673. configurable: true
  30674. });
  30675. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30676. get: function () {
  30677. if (this._texture) {
  30678. return this._texture._lodTextureHigh;
  30679. }
  30680. return null;
  30681. },
  30682. enumerable: true,
  30683. configurable: true
  30684. });
  30685. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30686. get: function () {
  30687. if (this._texture) {
  30688. return this._texture._lodTextureMid;
  30689. }
  30690. return null;
  30691. },
  30692. enumerable: true,
  30693. configurable: true
  30694. });
  30695. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30696. get: function () {
  30697. if (this._texture) {
  30698. return this._texture._lodTextureLow;
  30699. }
  30700. return null;
  30701. },
  30702. enumerable: true,
  30703. configurable: true
  30704. });
  30705. BaseTexture.prototype.dispose = function () {
  30706. if (!this._scene) {
  30707. return;
  30708. }
  30709. // Animations
  30710. this._scene.stopAnimation(this);
  30711. // Remove from scene
  30712. this._scene._removePendingData(this);
  30713. var index = this._scene.textures.indexOf(this);
  30714. if (index >= 0) {
  30715. this._scene.textures.splice(index, 1);
  30716. }
  30717. if (this._texture === undefined) {
  30718. return;
  30719. }
  30720. // Release
  30721. this.releaseInternalTexture();
  30722. // Callback
  30723. this.onDisposeObservable.notifyObservers(this);
  30724. this.onDisposeObservable.clear();
  30725. };
  30726. BaseTexture.prototype.serialize = function () {
  30727. if (!this.name) {
  30728. return null;
  30729. }
  30730. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30731. // Animations
  30732. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30733. return serializationObject;
  30734. };
  30735. BaseTexture.WhenAllReady = function (textures, callback) {
  30736. var numRemaining = textures.length;
  30737. if (numRemaining === 0) {
  30738. callback();
  30739. return;
  30740. }
  30741. var _loop_1 = function () {
  30742. texture = textures[i];
  30743. if (texture.isReady()) {
  30744. if (--numRemaining === 0) {
  30745. callback();
  30746. }
  30747. }
  30748. else {
  30749. onLoadObservable = texture.onLoadObservable;
  30750. var onLoadCallback_1 = function () {
  30751. onLoadObservable.removeCallback(onLoadCallback_1);
  30752. if (--numRemaining === 0) {
  30753. callback();
  30754. }
  30755. };
  30756. onLoadObservable.add(onLoadCallback_1);
  30757. }
  30758. };
  30759. var texture, onLoadObservable;
  30760. for (var i = 0; i < textures.length; i++) {
  30761. _loop_1();
  30762. }
  30763. };
  30764. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], BaseTexture.prototype, "name", void 0);
  30768. __decorate([
  30769. BABYLON.serialize("hasAlpha")
  30770. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30771. __decorate([
  30772. BABYLON.serialize()
  30773. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], BaseTexture.prototype, "level", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30780. __decorate([
  30781. BABYLON.serialize("coordinatesMode")
  30782. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], BaseTexture.prototype, "wrapU", void 0);
  30786. __decorate([
  30787. BABYLON.serialize()
  30788. ], BaseTexture.prototype, "wrapV", void 0);
  30789. __decorate([
  30790. BABYLON.serialize()
  30791. ], BaseTexture.prototype, "wrapR", void 0);
  30792. __decorate([
  30793. BABYLON.serialize()
  30794. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30795. __decorate([
  30796. BABYLON.serialize()
  30797. ], BaseTexture.prototype, "isCube", void 0);
  30798. __decorate([
  30799. BABYLON.serialize()
  30800. ], BaseTexture.prototype, "is3D", void 0);
  30801. __decorate([
  30802. BABYLON.serialize()
  30803. ], BaseTexture.prototype, "gammaSpace", void 0);
  30804. __decorate([
  30805. BABYLON.serialize()
  30806. ], BaseTexture.prototype, "invertZ", void 0);
  30807. __decorate([
  30808. BABYLON.serialize()
  30809. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30810. __decorate([
  30811. BABYLON.serialize()
  30812. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30813. __decorate([
  30814. BABYLON.serialize()
  30815. ], BaseTexture.prototype, "lodGenerationScale", null);
  30816. __decorate([
  30817. BABYLON.serialize()
  30818. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30819. return BaseTexture;
  30820. }());
  30821. BABYLON.BaseTexture = BaseTexture;
  30822. })(BABYLON || (BABYLON = {}));
  30823. //# sourceMappingURL=babylon.baseTexture.js.map
  30824. var BABYLON;
  30825. (function (BABYLON) {
  30826. var Texture = /** @class */ (function (_super) {
  30827. __extends(Texture, _super);
  30828. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30829. if (noMipmap === void 0) { noMipmap = false; }
  30830. if (invertY === void 0) { invertY = true; }
  30831. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30832. if (onLoad === void 0) { onLoad = null; }
  30833. if (onError === void 0) { onError = null; }
  30834. if (buffer === void 0) { buffer = null; }
  30835. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30836. var _this = _super.call(this, scene) || this;
  30837. _this.uOffset = 0;
  30838. _this.vOffset = 0;
  30839. _this.uScale = 1.0;
  30840. _this.vScale = 1.0;
  30841. _this.uAng = 0;
  30842. _this.vAng = 0;
  30843. _this.wAng = 0;
  30844. /**
  30845. * Defines the center of rotation (U)
  30846. */
  30847. _this.uRotationCenter = 0.5;
  30848. /**
  30849. * Defines the center of rotation (V)
  30850. */
  30851. _this.vRotationCenter = 0.5;
  30852. /**
  30853. * Defines the center of rotation (W)
  30854. */
  30855. _this.wRotationCenter = 0.5;
  30856. _this._isBlocking = true;
  30857. _this.name = url || "";
  30858. _this.url = url;
  30859. _this._noMipmap = noMipmap;
  30860. _this._invertY = invertY;
  30861. _this._samplingMode = samplingMode;
  30862. _this._buffer = buffer;
  30863. _this._deleteBuffer = deleteBuffer;
  30864. if (format) {
  30865. _this._format = format;
  30866. }
  30867. scene = _this.getScene();
  30868. if (!scene) {
  30869. return _this;
  30870. }
  30871. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30872. var load = function () {
  30873. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30874. _this.onLoadObservable.notifyObservers(_this);
  30875. }
  30876. if (onLoad) {
  30877. onLoad();
  30878. }
  30879. if (!_this.isBlocking && scene) {
  30880. scene.resetCachedMaterial();
  30881. }
  30882. };
  30883. if (!_this.url) {
  30884. _this._delayedOnLoad = load;
  30885. _this._delayedOnError = onError;
  30886. return _this;
  30887. }
  30888. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30889. if (!_this._texture) {
  30890. if (!scene.useDelayedTextureLoading) {
  30891. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30892. if (deleteBuffer) {
  30893. delete _this._buffer;
  30894. }
  30895. }
  30896. else {
  30897. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30898. _this._delayedOnLoad = load;
  30899. _this._delayedOnError = onError;
  30900. }
  30901. }
  30902. else {
  30903. if (_this._texture.isReady) {
  30904. BABYLON.Tools.SetImmediate(function () { return load(); });
  30905. }
  30906. else {
  30907. _this._texture.onLoadedObservable.add(load);
  30908. }
  30909. }
  30910. return _this;
  30911. }
  30912. Object.defineProperty(Texture.prototype, "noMipmap", {
  30913. get: function () {
  30914. return this._noMipmap;
  30915. },
  30916. enumerable: true,
  30917. configurable: true
  30918. });
  30919. Object.defineProperty(Texture.prototype, "isBlocking", {
  30920. get: function () {
  30921. return this._isBlocking;
  30922. },
  30923. set: function (value) {
  30924. this._isBlocking = value;
  30925. },
  30926. enumerable: true,
  30927. configurable: true
  30928. });
  30929. Object.defineProperty(Texture.prototype, "samplingMode", {
  30930. get: function () {
  30931. return this._samplingMode;
  30932. },
  30933. enumerable: true,
  30934. configurable: true
  30935. });
  30936. /**
  30937. * Update the url (and optional buffer) of this texture if url was null during construction.
  30938. * @param url the url of the texture
  30939. * @param buffer the buffer of the texture (defaults to null)
  30940. */
  30941. Texture.prototype.updateURL = function (url, buffer) {
  30942. if (buffer === void 0) { buffer = null; }
  30943. if (this.url) {
  30944. throw new Error("URL is already set");
  30945. }
  30946. this.url = url;
  30947. this._buffer = buffer;
  30948. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30949. this.delayLoad();
  30950. };
  30951. Texture.prototype.delayLoad = function () {
  30952. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30953. return;
  30954. }
  30955. var scene = this.getScene();
  30956. if (!scene) {
  30957. return;
  30958. }
  30959. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30960. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30961. if (!this._texture) {
  30962. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30963. if (this._deleteBuffer) {
  30964. delete this._buffer;
  30965. }
  30966. }
  30967. else {
  30968. if (this._delayedOnLoad) {
  30969. if (this._texture.isReady) {
  30970. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30971. }
  30972. else {
  30973. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30974. }
  30975. }
  30976. }
  30977. this._delayedOnLoad = null;
  30978. this._delayedOnError = null;
  30979. };
  30980. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30981. if (!this._texture) {
  30982. return;
  30983. }
  30984. var scene = this.getScene();
  30985. if (!scene) {
  30986. return;
  30987. }
  30988. this._samplingMode = samplingMode;
  30989. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30990. };
  30991. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30992. x *= this.uScale;
  30993. y *= this.vScale;
  30994. x -= this.uRotationCenter * this.uScale;
  30995. y -= this.vRotationCenter * this.vScale;
  30996. z -= this.wRotationCenter;
  30997. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30998. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30999. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31000. t.z += this.wRotationCenter;
  31001. };
  31002. Texture.prototype.getTextureMatrix = function () {
  31003. var _this = this;
  31004. if (this.uOffset === this._cachedUOffset &&
  31005. this.vOffset === this._cachedVOffset &&
  31006. this.uScale === this._cachedUScale &&
  31007. this.vScale === this._cachedVScale &&
  31008. this.uAng === this._cachedUAng &&
  31009. this.vAng === this._cachedVAng &&
  31010. this.wAng === this._cachedWAng) {
  31011. return this._cachedTextureMatrix;
  31012. }
  31013. this._cachedUOffset = this.uOffset;
  31014. this._cachedVOffset = this.vOffset;
  31015. this._cachedUScale = this.uScale;
  31016. this._cachedVScale = this.vScale;
  31017. this._cachedUAng = this.uAng;
  31018. this._cachedVAng = this.vAng;
  31019. this._cachedWAng = this.wAng;
  31020. if (!this._cachedTextureMatrix) {
  31021. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31022. this._rowGenerationMatrix = new BABYLON.Matrix();
  31023. this._t0 = BABYLON.Vector3.Zero();
  31024. this._t1 = BABYLON.Vector3.Zero();
  31025. this._t2 = BABYLON.Vector3.Zero();
  31026. }
  31027. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31028. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31029. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31030. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31031. this._t1.subtractInPlace(this._t0);
  31032. this._t2.subtractInPlace(this._t0);
  31033. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31034. this._cachedTextureMatrix.m[0] = this._t1.x;
  31035. this._cachedTextureMatrix.m[1] = this._t1.y;
  31036. this._cachedTextureMatrix.m[2] = this._t1.z;
  31037. this._cachedTextureMatrix.m[4] = this._t2.x;
  31038. this._cachedTextureMatrix.m[5] = this._t2.y;
  31039. this._cachedTextureMatrix.m[6] = this._t2.z;
  31040. this._cachedTextureMatrix.m[8] = this._t0.x;
  31041. this._cachedTextureMatrix.m[9] = this._t0.y;
  31042. this._cachedTextureMatrix.m[10] = this._t0.z;
  31043. var scene = this.getScene();
  31044. if (!scene) {
  31045. return this._cachedTextureMatrix;
  31046. }
  31047. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31048. return mat.hasTexture(_this);
  31049. });
  31050. return this._cachedTextureMatrix;
  31051. };
  31052. Texture.prototype.getReflectionTextureMatrix = function () {
  31053. var _this = this;
  31054. var scene = this.getScene();
  31055. if (!scene) {
  31056. return this._cachedTextureMatrix;
  31057. }
  31058. if (this.uOffset === this._cachedUOffset &&
  31059. this.vOffset === this._cachedVOffset &&
  31060. this.uScale === this._cachedUScale &&
  31061. this.vScale === this._cachedVScale &&
  31062. this.coordinatesMode === this._cachedCoordinatesMode) {
  31063. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31064. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31065. return this._cachedTextureMatrix;
  31066. }
  31067. }
  31068. else {
  31069. return this._cachedTextureMatrix;
  31070. }
  31071. }
  31072. if (!this._cachedTextureMatrix) {
  31073. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31074. }
  31075. if (!this._projectionModeMatrix) {
  31076. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31077. }
  31078. this._cachedUOffset = this.uOffset;
  31079. this._cachedVOffset = this.vOffset;
  31080. this._cachedUScale = this.uScale;
  31081. this._cachedVScale = this.vScale;
  31082. this._cachedCoordinatesMode = this.coordinatesMode;
  31083. switch (this.coordinatesMode) {
  31084. case Texture.PLANAR_MODE:
  31085. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31086. this._cachedTextureMatrix[0] = this.uScale;
  31087. this._cachedTextureMatrix[5] = this.vScale;
  31088. this._cachedTextureMatrix[12] = this.uOffset;
  31089. this._cachedTextureMatrix[13] = this.vOffset;
  31090. break;
  31091. case Texture.PROJECTION_MODE:
  31092. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31093. this._projectionModeMatrix.m[0] = 0.5;
  31094. this._projectionModeMatrix.m[5] = -0.5;
  31095. this._projectionModeMatrix.m[10] = 0.0;
  31096. this._projectionModeMatrix.m[12] = 0.5;
  31097. this._projectionModeMatrix.m[13] = 0.5;
  31098. this._projectionModeMatrix.m[14] = 1.0;
  31099. this._projectionModeMatrix.m[15] = 1.0;
  31100. var projectionMatrix = scene.getProjectionMatrix();
  31101. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31102. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31103. break;
  31104. default:
  31105. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31106. break;
  31107. }
  31108. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31109. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31110. });
  31111. return this._cachedTextureMatrix;
  31112. };
  31113. Texture.prototype.clone = function () {
  31114. var _this = this;
  31115. return BABYLON.SerializationHelper.Clone(function () {
  31116. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31117. }, this);
  31118. };
  31119. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31120. get: function () {
  31121. if (!this._onLoadObservable) {
  31122. this._onLoadObservable = new BABYLON.Observable();
  31123. }
  31124. return this._onLoadObservable;
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. Texture.prototype.serialize = function () {
  31130. var serializationObject = _super.prototype.serialize.call(this);
  31131. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31132. serializationObject.base64String = this._buffer;
  31133. serializationObject.name = serializationObject.name.replace("data:", "");
  31134. }
  31135. serializationObject.invertY = this._invertY;
  31136. serializationObject.samplingMode = this.samplingMode;
  31137. return serializationObject;
  31138. };
  31139. Texture.prototype.getClassName = function () {
  31140. return "Texture";
  31141. };
  31142. Texture.prototype.dispose = function () {
  31143. _super.prototype.dispose.call(this);
  31144. if (this.onLoadObservable) {
  31145. this.onLoadObservable.clear();
  31146. this._onLoadObservable = null;
  31147. }
  31148. this._delayedOnLoad = null;
  31149. this._delayedOnError = null;
  31150. };
  31151. // Statics
  31152. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31153. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31154. if (onLoad === void 0) { onLoad = null; }
  31155. if (onError === void 0) { onError = null; }
  31156. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31157. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31158. };
  31159. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31160. if (parsedTexture.customType) {
  31161. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31162. // Update Sampling Mode
  31163. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31164. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31165. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31166. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31167. }
  31168. }
  31169. return parsedCustomTexture;
  31170. }
  31171. if (parsedTexture.isCube) {
  31172. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31173. }
  31174. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31175. return null;
  31176. }
  31177. var texture = BABYLON.SerializationHelper.Parse(function () {
  31178. var generateMipMaps = true;
  31179. if (parsedTexture.noMipmap) {
  31180. generateMipMaps = false;
  31181. }
  31182. if (parsedTexture.mirrorPlane) {
  31183. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31184. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31185. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31186. return mirrorTexture;
  31187. }
  31188. else if (parsedTexture.isRenderTarget) {
  31189. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31190. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31191. return renderTargetTexture;
  31192. }
  31193. else {
  31194. var texture;
  31195. if (parsedTexture.base64String) {
  31196. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31197. }
  31198. else {
  31199. var url = rootUrl + parsedTexture.name;
  31200. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31201. url = parsedTexture.url;
  31202. }
  31203. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31204. }
  31205. return texture;
  31206. }
  31207. }, parsedTexture, scene);
  31208. // Update Sampling Mode
  31209. if (parsedTexture.samplingMode) {
  31210. var sampling = parsedTexture.samplingMode;
  31211. if (texture._samplingMode !== sampling) {
  31212. texture.updateSamplingMode(sampling);
  31213. }
  31214. }
  31215. // Animations
  31216. if (parsedTexture.animations) {
  31217. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31218. var parsedAnimation = parsedTexture.animations[animationIndex];
  31219. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31220. }
  31221. }
  31222. return texture;
  31223. };
  31224. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31225. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31226. if (noMipmap === void 0) { noMipmap = false; }
  31227. if (invertY === void 0) { invertY = true; }
  31228. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31229. if (onLoad === void 0) { onLoad = null; }
  31230. if (onError === void 0) { onError = null; }
  31231. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31232. if (name.substr(0, 5) !== "data:") {
  31233. name = "data:" + name;
  31234. }
  31235. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31236. };
  31237. // Constants
  31238. Texture.NEAREST_SAMPLINGMODE = 1;
  31239. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31240. Texture.BILINEAR_SAMPLINGMODE = 2;
  31241. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31242. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31243. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31244. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31245. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31246. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31247. Texture.NEAREST_LINEAR = 7;
  31248. Texture.NEAREST_NEAREST = 8;
  31249. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31250. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31251. Texture.LINEAR_LINEAR = 11;
  31252. Texture.LINEAR_NEAREST = 12;
  31253. Texture.EXPLICIT_MODE = 0;
  31254. Texture.SPHERICAL_MODE = 1;
  31255. Texture.PLANAR_MODE = 2;
  31256. Texture.CUBIC_MODE = 3;
  31257. Texture.PROJECTION_MODE = 4;
  31258. Texture.SKYBOX_MODE = 5;
  31259. Texture.INVCUBIC_MODE = 6;
  31260. Texture.EQUIRECTANGULAR_MODE = 7;
  31261. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31262. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31263. Texture.CLAMP_ADDRESSMODE = 0;
  31264. Texture.WRAP_ADDRESSMODE = 1;
  31265. Texture.MIRROR_ADDRESSMODE = 2;
  31266. /**
  31267. * 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
  31268. */
  31269. Texture.UseSerializedUrlIfAny = false;
  31270. __decorate([
  31271. BABYLON.serialize()
  31272. ], Texture.prototype, "url", void 0);
  31273. __decorate([
  31274. BABYLON.serialize()
  31275. ], Texture.prototype, "uOffset", void 0);
  31276. __decorate([
  31277. BABYLON.serialize()
  31278. ], Texture.prototype, "vOffset", void 0);
  31279. __decorate([
  31280. BABYLON.serialize()
  31281. ], Texture.prototype, "uScale", void 0);
  31282. __decorate([
  31283. BABYLON.serialize()
  31284. ], Texture.prototype, "vScale", void 0);
  31285. __decorate([
  31286. BABYLON.serialize()
  31287. ], Texture.prototype, "uAng", void 0);
  31288. __decorate([
  31289. BABYLON.serialize()
  31290. ], Texture.prototype, "vAng", void 0);
  31291. __decorate([
  31292. BABYLON.serialize()
  31293. ], Texture.prototype, "wAng", void 0);
  31294. __decorate([
  31295. BABYLON.serialize()
  31296. ], Texture.prototype, "uRotationCenter", void 0);
  31297. __decorate([
  31298. BABYLON.serialize()
  31299. ], Texture.prototype, "vRotationCenter", void 0);
  31300. __decorate([
  31301. BABYLON.serialize()
  31302. ], Texture.prototype, "wRotationCenter", void 0);
  31303. __decorate([
  31304. BABYLON.serialize()
  31305. ], Texture.prototype, "isBlocking", null);
  31306. return Texture;
  31307. }(BABYLON.BaseTexture));
  31308. BABYLON.Texture = Texture;
  31309. })(BABYLON || (BABYLON = {}));
  31310. //# sourceMappingURL=babylon.texture.js.map
  31311. var BABYLON;
  31312. (function (BABYLON) {
  31313. /**
  31314. * @hidden
  31315. **/
  31316. var _InstancesBatch = /** @class */ (function () {
  31317. function _InstancesBatch() {
  31318. this.mustReturn = false;
  31319. this.visibleInstances = new Array();
  31320. this.renderSelf = new Array();
  31321. }
  31322. return _InstancesBatch;
  31323. }());
  31324. BABYLON._InstancesBatch = _InstancesBatch;
  31325. var Mesh = /** @class */ (function (_super) {
  31326. __extends(Mesh, _super);
  31327. /**
  31328. * @constructor
  31329. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31330. * @param {Scene} scene The scene to add this mesh to.
  31331. * @param {Node} parent The parent of this mesh, if it has one
  31332. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31333. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31334. * When false, achieved by calling a clone(), also passing False.
  31335. * This will make creation of children, recursive.
  31336. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31337. */
  31338. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31339. if (scene === void 0) { scene = null; }
  31340. if (parent === void 0) { parent = null; }
  31341. if (source === void 0) { source = null; }
  31342. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31343. var _this = _super.call(this, name, scene) || this;
  31344. // Events
  31345. /**
  31346. * An event triggered before rendering the mesh
  31347. */
  31348. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31349. /**
  31350. * An event triggered after rendering the mesh
  31351. */
  31352. _this.onAfterRenderObservable = new BABYLON.Observable();
  31353. /**
  31354. * An event triggered before drawing the mesh
  31355. */
  31356. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31357. // Members
  31358. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31359. _this.instances = new Array();
  31360. _this._LODLevels = new Array();
  31361. _this._visibleInstances = {};
  31362. _this._renderIdForInstances = new Array();
  31363. _this._batchCache = new _InstancesBatch();
  31364. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31365. // Use by builder only to know what orientation were the mesh build in.
  31366. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31367. _this.overrideMaterialSideOrientation = null;
  31368. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31369. // Will be used to save a source mesh reference, If any
  31370. _this._source = null;
  31371. scene = _this.getScene();
  31372. if (source) {
  31373. // Geometry
  31374. if (source._geometry) {
  31375. source._geometry.applyToMesh(_this);
  31376. }
  31377. // Deep copy
  31378. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31379. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31380. // Source mesh
  31381. _this._source = source;
  31382. // Metadata
  31383. if (source.metadata && source.metadata.clone) {
  31384. _this.metadata = source.metadata.clone();
  31385. }
  31386. else {
  31387. _this.metadata = source.metadata;
  31388. }
  31389. // Tags
  31390. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31391. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31392. }
  31393. // Parent
  31394. _this.parent = source.parent;
  31395. // Pivot
  31396. _this.setPivotMatrix(source.getPivotMatrix());
  31397. _this.id = name + "." + source.id;
  31398. // Material
  31399. _this.material = source.material;
  31400. var index;
  31401. if (!doNotCloneChildren) {
  31402. // Children
  31403. var directDescendants = source.getDescendants(true);
  31404. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31405. var child = directDescendants[index_1];
  31406. if (child.clone) {
  31407. child.clone(name + "." + child.name, _this);
  31408. }
  31409. }
  31410. }
  31411. // Physics clone
  31412. var physicsEngine = _this.getScene().getPhysicsEngine();
  31413. if (clonePhysicsImpostor && physicsEngine) {
  31414. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31415. if (impostor) {
  31416. _this.physicsImpostor = impostor.clone(_this);
  31417. }
  31418. }
  31419. // Particles
  31420. for (index = 0; index < scene.particleSystems.length; index++) {
  31421. var system = scene.particleSystems[index];
  31422. if (system.emitter === source) {
  31423. system.clone(system.name, _this);
  31424. }
  31425. }
  31426. _this.computeWorldMatrix(true);
  31427. }
  31428. // Parent
  31429. if (parent !== null) {
  31430. _this.parent = parent;
  31431. }
  31432. return _this;
  31433. }
  31434. Object.defineProperty(Mesh, "FRONTSIDE", {
  31435. /**
  31436. * Mesh side orientation : usually the external or front surface
  31437. */
  31438. get: function () {
  31439. return Mesh._FRONTSIDE;
  31440. },
  31441. enumerable: true,
  31442. configurable: true
  31443. });
  31444. Object.defineProperty(Mesh, "BACKSIDE", {
  31445. /**
  31446. * Mesh side orientation : usually the internal or back surface
  31447. */
  31448. get: function () {
  31449. return Mesh._BACKSIDE;
  31450. },
  31451. enumerable: true,
  31452. configurable: true
  31453. });
  31454. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31455. /**
  31456. * Mesh side orientation : both internal and external or front and back surfaces
  31457. */
  31458. get: function () {
  31459. return Mesh._DOUBLESIDE;
  31460. },
  31461. enumerable: true,
  31462. configurable: true
  31463. });
  31464. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31465. /**
  31466. * Mesh side orientation : by default, `FRONTSIDE`
  31467. */
  31468. get: function () {
  31469. return Mesh._DEFAULTSIDE;
  31470. },
  31471. enumerable: true,
  31472. configurable: true
  31473. });
  31474. Object.defineProperty(Mesh, "NO_CAP", {
  31475. /**
  31476. * Mesh cap setting : no cap
  31477. */
  31478. get: function () {
  31479. return Mesh._NO_CAP;
  31480. },
  31481. enumerable: true,
  31482. configurable: true
  31483. });
  31484. Object.defineProperty(Mesh, "CAP_START", {
  31485. /**
  31486. * Mesh cap setting : one cap at the beginning of the mesh
  31487. */
  31488. get: function () {
  31489. return Mesh._CAP_START;
  31490. },
  31491. enumerable: true,
  31492. configurable: true
  31493. });
  31494. Object.defineProperty(Mesh, "CAP_END", {
  31495. /**
  31496. * Mesh cap setting : one cap at the end of the mesh
  31497. */
  31498. get: function () {
  31499. return Mesh._CAP_END;
  31500. },
  31501. enumerable: true,
  31502. configurable: true
  31503. });
  31504. Object.defineProperty(Mesh, "CAP_ALL", {
  31505. /**
  31506. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31507. */
  31508. get: function () {
  31509. return Mesh._CAP_ALL;
  31510. },
  31511. enumerable: true,
  31512. configurable: true
  31513. });
  31514. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31515. set: function (callback) {
  31516. if (this._onBeforeDrawObserver) {
  31517. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31518. }
  31519. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31520. },
  31521. enumerable: true,
  31522. configurable: true
  31523. });
  31524. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31525. get: function () {
  31526. return this._morphTargetManager;
  31527. },
  31528. set: function (value) {
  31529. if (this._morphTargetManager === value) {
  31530. return;
  31531. }
  31532. this._morphTargetManager = value;
  31533. this._syncGeometryWithMorphTargetManager();
  31534. },
  31535. enumerable: true,
  31536. configurable: true
  31537. });
  31538. Object.defineProperty(Mesh.prototype, "source", {
  31539. get: function () {
  31540. return this._source;
  31541. },
  31542. enumerable: true,
  31543. configurable: true
  31544. });
  31545. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31546. get: function () {
  31547. return this._unIndexed;
  31548. },
  31549. set: function (value) {
  31550. if (this._unIndexed !== value) {
  31551. this._unIndexed = value;
  31552. this._markSubMeshesAsAttributesDirty();
  31553. }
  31554. },
  31555. enumerable: true,
  31556. configurable: true
  31557. });
  31558. // Methods
  31559. /**
  31560. * Returns the string "Mesh".
  31561. */
  31562. Mesh.prototype.getClassName = function () {
  31563. return "Mesh";
  31564. };
  31565. /**
  31566. * Returns a string.
  31567. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31568. */
  31569. Mesh.prototype.toString = function (fullDetails) {
  31570. var ret = _super.prototype.toString.call(this, fullDetails);
  31571. ret += ", n vertices: " + this.getTotalVertices();
  31572. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31573. if (this.animations) {
  31574. for (var i = 0; i < this.animations.length; i++) {
  31575. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31576. }
  31577. }
  31578. if (fullDetails) {
  31579. if (this._geometry) {
  31580. var ib = this.getIndices();
  31581. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31582. if (vb && ib) {
  31583. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31584. }
  31585. }
  31586. else {
  31587. ret += ", flat shading: UNKNOWN";
  31588. }
  31589. }
  31590. return ret;
  31591. };
  31592. Mesh.prototype._unBindEffect = function () {
  31593. _super.prototype._unBindEffect.call(this);
  31594. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31595. var instance = _a[_i];
  31596. instance._unBindEffect();
  31597. }
  31598. };
  31599. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31600. /**
  31601. * True if the mesh has some Levels Of Details (LOD).
  31602. * Returns a boolean.
  31603. */
  31604. get: function () {
  31605. return this._LODLevels.length > 0;
  31606. },
  31607. enumerable: true,
  31608. configurable: true
  31609. });
  31610. /**
  31611. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31612. * @returns an array of {BABYLON.MeshLODLevel}
  31613. */
  31614. Mesh.prototype.getLODLevels = function () {
  31615. return this._LODLevels;
  31616. };
  31617. Mesh.prototype._sortLODLevels = function () {
  31618. this._LODLevels.sort(function (a, b) {
  31619. if (a.distance < b.distance) {
  31620. return 1;
  31621. }
  31622. if (a.distance > b.distance) {
  31623. return -1;
  31624. }
  31625. return 0;
  31626. });
  31627. };
  31628. /**
  31629. * Add a mesh as LOD level triggered at the given distance.
  31630. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31631. * @param distance The distance from the center of the object to show this level
  31632. * @param mesh The mesh to be added as LOD level (can be null)
  31633. * @return This mesh (for chaining)
  31634. */
  31635. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31636. if (mesh && mesh._masterMesh) {
  31637. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31638. return this;
  31639. }
  31640. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31641. this._LODLevels.push(level);
  31642. if (mesh) {
  31643. mesh._masterMesh = this;
  31644. }
  31645. this._sortLODLevels();
  31646. return this;
  31647. };
  31648. /**
  31649. * Returns the LOD level mesh at the passed distance or null if not found.
  31650. * It is related to the method `addLODLevel(distance, mesh)`.
  31651. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31652. * Returns an object Mesh or `null`.
  31653. */
  31654. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31655. for (var index = 0; index < this._LODLevels.length; index++) {
  31656. var level = this._LODLevels[index];
  31657. if (level.distance === distance) {
  31658. return level.mesh;
  31659. }
  31660. }
  31661. return null;
  31662. };
  31663. /**
  31664. * Remove a mesh from the LOD array
  31665. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31666. * @param {Mesh} mesh The mesh to be removed.
  31667. * @return {Mesh} This mesh (for chaining)
  31668. */
  31669. Mesh.prototype.removeLODLevel = function (mesh) {
  31670. for (var index = 0; index < this._LODLevels.length; index++) {
  31671. if (this._LODLevels[index].mesh === mesh) {
  31672. this._LODLevels.splice(index, 1);
  31673. if (mesh) {
  31674. mesh._masterMesh = null;
  31675. }
  31676. }
  31677. }
  31678. this._sortLODLevels();
  31679. return this;
  31680. };
  31681. /**
  31682. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31683. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31684. */
  31685. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31686. if (!this._LODLevels || this._LODLevels.length === 0) {
  31687. return this;
  31688. }
  31689. var bSphere;
  31690. if (boundingSphere) {
  31691. bSphere = boundingSphere;
  31692. }
  31693. else {
  31694. var boundingInfo = this.getBoundingInfo();
  31695. bSphere = boundingInfo.boundingSphere;
  31696. }
  31697. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31698. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31699. if (this.onLODLevelSelection) {
  31700. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31701. }
  31702. return this;
  31703. }
  31704. for (var index = 0; index < this._LODLevels.length; index++) {
  31705. var level = this._LODLevels[index];
  31706. if (level.distance < distanceToCamera) {
  31707. if (level.mesh) {
  31708. level.mesh._preActivate();
  31709. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31710. }
  31711. if (this.onLODLevelSelection) {
  31712. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31713. }
  31714. return level.mesh;
  31715. }
  31716. }
  31717. if (this.onLODLevelSelection) {
  31718. this.onLODLevelSelection(distanceToCamera, this, this);
  31719. }
  31720. return this;
  31721. };
  31722. Object.defineProperty(Mesh.prototype, "geometry", {
  31723. /**
  31724. * Returns the mesh internal Geometry object.
  31725. */
  31726. get: function () {
  31727. return this._geometry;
  31728. },
  31729. enumerable: true,
  31730. configurable: true
  31731. });
  31732. /**
  31733. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31734. */
  31735. Mesh.prototype.getTotalVertices = function () {
  31736. if (this._geometry === null || this._geometry === undefined) {
  31737. return 0;
  31738. }
  31739. return this._geometry.getTotalVertices();
  31740. };
  31741. /**
  31742. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31743. * 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.
  31744. * You can force the copy with forceCopy === true
  31745. * Returns null if the mesh has no geometry or no vertex buffer.
  31746. * Possible `kind` values :
  31747. * - BABYLON.VertexBuffer.PositionKind
  31748. * - BABYLON.VertexBuffer.UVKind
  31749. * - BABYLON.VertexBuffer.UV2Kind
  31750. * - BABYLON.VertexBuffer.UV3Kind
  31751. * - BABYLON.VertexBuffer.UV4Kind
  31752. * - BABYLON.VertexBuffer.UV5Kind
  31753. * - BABYLON.VertexBuffer.UV6Kind
  31754. * - BABYLON.VertexBuffer.ColorKind
  31755. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31756. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31757. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31758. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31759. */
  31760. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31761. if (!this._geometry) {
  31762. return null;
  31763. }
  31764. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31765. };
  31766. /**
  31767. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31768. * Returns `null` if the mesh has no geometry.
  31769. * Possible `kind` values :
  31770. * - BABYLON.VertexBuffer.PositionKind
  31771. * - BABYLON.VertexBuffer.UVKind
  31772. * - BABYLON.VertexBuffer.UV2Kind
  31773. * - BABYLON.VertexBuffer.UV3Kind
  31774. * - BABYLON.VertexBuffer.UV4Kind
  31775. * - BABYLON.VertexBuffer.UV5Kind
  31776. * - BABYLON.VertexBuffer.UV6Kind
  31777. * - BABYLON.VertexBuffer.ColorKind
  31778. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31779. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31780. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31781. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31782. */
  31783. Mesh.prototype.getVertexBuffer = function (kind) {
  31784. if (!this._geometry) {
  31785. return null;
  31786. }
  31787. return this._geometry.getVertexBuffer(kind);
  31788. };
  31789. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31790. if (!this._geometry) {
  31791. if (this._delayInfo) {
  31792. return this._delayInfo.indexOf(kind) !== -1;
  31793. }
  31794. return false;
  31795. }
  31796. return this._geometry.isVerticesDataPresent(kind);
  31797. };
  31798. /**
  31799. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31800. * Possible `kind` values :
  31801. * - BABYLON.VertexBuffer.PositionKind
  31802. * - BABYLON.VertexBuffer.UVKind
  31803. * - BABYLON.VertexBuffer.UV2Kind
  31804. * - BABYLON.VertexBuffer.UV3Kind
  31805. * - BABYLON.VertexBuffer.UV4Kind
  31806. * - BABYLON.VertexBuffer.UV5Kind
  31807. * - BABYLON.VertexBuffer.UV6Kind
  31808. * - BABYLON.VertexBuffer.ColorKind
  31809. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31810. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31811. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31812. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31813. */
  31814. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31815. if (!this._geometry) {
  31816. if (this._delayInfo) {
  31817. return this._delayInfo.indexOf(kind) !== -1;
  31818. }
  31819. return false;
  31820. }
  31821. return this._geometry.isVertexBufferUpdatable(kind);
  31822. };
  31823. /**
  31824. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31825. * Possible `kind` values :
  31826. * - BABYLON.VertexBuffer.PositionKind
  31827. * - BABYLON.VertexBuffer.UVKind
  31828. * - BABYLON.VertexBuffer.UV2Kind
  31829. * - BABYLON.VertexBuffer.UV3Kind
  31830. * - BABYLON.VertexBuffer.UV4Kind
  31831. * - BABYLON.VertexBuffer.UV5Kind
  31832. * - BABYLON.VertexBuffer.UV6Kind
  31833. * - BABYLON.VertexBuffer.ColorKind
  31834. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31835. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31836. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31837. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31838. */
  31839. Mesh.prototype.getVerticesDataKinds = function () {
  31840. if (!this._geometry) {
  31841. var result = new Array();
  31842. if (this._delayInfo) {
  31843. this._delayInfo.forEach(function (kind, index, array) {
  31844. result.push(kind);
  31845. });
  31846. }
  31847. return result;
  31848. }
  31849. return this._geometry.getVerticesDataKinds();
  31850. };
  31851. /**
  31852. * Returns a positive integer : the total number of indices in this mesh geometry.
  31853. * Returns zero if the mesh has no geometry.
  31854. */
  31855. Mesh.prototype.getTotalIndices = function () {
  31856. if (!this._geometry) {
  31857. return 0;
  31858. }
  31859. return this._geometry.getTotalIndices();
  31860. };
  31861. /**
  31862. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31863. * 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.
  31864. * Returns an empty array if the mesh has no geometry.
  31865. */
  31866. Mesh.prototype.getIndices = function (copyWhenShared) {
  31867. if (!this._geometry) {
  31868. return [];
  31869. }
  31870. return this._geometry.getIndices(copyWhenShared);
  31871. };
  31872. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31873. get: function () {
  31874. return this._masterMesh !== null && this._masterMesh !== undefined;
  31875. },
  31876. enumerable: true,
  31877. configurable: true
  31878. });
  31879. /**
  31880. * Determine if the current mesh is ready to be rendered
  31881. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31882. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31883. * @returns true if all associated assets are ready (material, textures, shaders)
  31884. */
  31885. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31886. if (completeCheck === void 0) { completeCheck = false; }
  31887. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31888. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31889. return false;
  31890. }
  31891. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31892. return false;
  31893. }
  31894. if (!this.subMeshes || this.subMeshes.length === 0) {
  31895. return true;
  31896. }
  31897. if (!completeCheck) {
  31898. return true;
  31899. }
  31900. var engine = this.getEngine();
  31901. var scene = this.getScene();
  31902. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31903. this.computeWorldMatrix();
  31904. var mat = this.material || scene.defaultMaterial;
  31905. if (mat) {
  31906. if (mat.storeEffectOnSubMeshes) {
  31907. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31908. var subMesh = _a[_i];
  31909. var effectiveMaterial = subMesh.getMaterial();
  31910. if (effectiveMaterial) {
  31911. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31912. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31913. return false;
  31914. }
  31915. }
  31916. else {
  31917. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31918. return false;
  31919. }
  31920. }
  31921. }
  31922. }
  31923. }
  31924. else {
  31925. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31926. return false;
  31927. }
  31928. }
  31929. }
  31930. // Shadows
  31931. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31932. var light = _c[_b];
  31933. var generator = light.getShadowGenerator();
  31934. if (generator) {
  31935. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31936. var subMesh = _e[_d];
  31937. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31938. return false;
  31939. }
  31940. }
  31941. }
  31942. }
  31943. // LOD
  31944. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31945. var lod = _g[_f];
  31946. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31947. return false;
  31948. }
  31949. }
  31950. return true;
  31951. };
  31952. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31953. /**
  31954. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31955. * This property is pertinent only for updatable parametric shapes.
  31956. */
  31957. get: function () {
  31958. return this._areNormalsFrozen;
  31959. },
  31960. enumerable: true,
  31961. configurable: true
  31962. });
  31963. /**
  31964. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31965. * It has no effect at all on other shapes.
  31966. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31967. * Returns the Mesh.
  31968. */
  31969. Mesh.prototype.freezeNormals = function () {
  31970. this._areNormalsFrozen = true;
  31971. return this;
  31972. };
  31973. /**
  31974. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31975. * It has no effect at all on other shapes.
  31976. * It reactivates the mesh normals computation if it was previously frozen.
  31977. * Returns the Mesh.
  31978. */
  31979. Mesh.prototype.unfreezeNormals = function () {
  31980. this._areNormalsFrozen = false;
  31981. return this;
  31982. };
  31983. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31984. /**
  31985. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31986. */
  31987. set: function (count) {
  31988. this._overridenInstanceCount = count;
  31989. },
  31990. enumerable: true,
  31991. configurable: true
  31992. });
  31993. // Methods
  31994. Mesh.prototype._preActivate = function () {
  31995. var sceneRenderId = this.getScene().getRenderId();
  31996. if (this._preActivateId === sceneRenderId) {
  31997. return this;
  31998. }
  31999. this._preActivateId = sceneRenderId;
  32000. this._visibleInstances = null;
  32001. return this;
  32002. };
  32003. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32004. if (this._visibleInstances) {
  32005. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32006. }
  32007. return this;
  32008. };
  32009. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32010. if (!this._visibleInstances) {
  32011. this._visibleInstances = {};
  32012. this._visibleInstances.defaultRenderId = renderId;
  32013. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32014. }
  32015. if (!this._visibleInstances[renderId]) {
  32016. this._visibleInstances[renderId] = new Array();
  32017. }
  32018. this._visibleInstances[renderId].push(instance);
  32019. return this;
  32020. };
  32021. /**
  32022. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32023. * This means the mesh underlying bounding box and sphere are recomputed.
  32024. * Returns the Mesh.
  32025. */
  32026. Mesh.prototype.refreshBoundingInfo = function () {
  32027. return this._refreshBoundingInfo(false);
  32028. };
  32029. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32030. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32031. return this;
  32032. }
  32033. var data = this._getPositionData(applySkeleton);
  32034. if (data) {
  32035. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32036. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32037. }
  32038. if (this.subMeshes) {
  32039. for (var index = 0; index < this.subMeshes.length; index++) {
  32040. this.subMeshes[index].refreshBoundingInfo();
  32041. }
  32042. }
  32043. this._updateBoundingInfo();
  32044. return this;
  32045. };
  32046. Mesh.prototype._getPositionData = function (applySkeleton) {
  32047. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32048. if (data && applySkeleton && this.skeleton) {
  32049. data = BABYLON.Tools.Slice(data);
  32050. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32051. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32052. if (matricesWeightsData && matricesIndicesData) {
  32053. var needExtras = this.numBoneInfluencers > 4;
  32054. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32055. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32056. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32057. var tempVector = BABYLON.Tmp.Vector3[0];
  32058. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32059. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32060. var matWeightIdx = 0;
  32061. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32062. finalMatrix.reset();
  32063. var inf;
  32064. var weight;
  32065. for (inf = 0; inf < 4; inf++) {
  32066. weight = matricesWeightsData[matWeightIdx + inf];
  32067. if (weight <= 0)
  32068. break;
  32069. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32070. finalMatrix.addToSelf(tempMatrix);
  32071. }
  32072. if (needExtras) {
  32073. for (inf = 0; inf < 4; inf++) {
  32074. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32075. if (weight <= 0)
  32076. break;
  32077. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32078. finalMatrix.addToSelf(tempMatrix);
  32079. }
  32080. }
  32081. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32082. tempVector.toArray(data, index);
  32083. }
  32084. }
  32085. }
  32086. return data;
  32087. };
  32088. Mesh.prototype._createGlobalSubMesh = function (force) {
  32089. var totalVertices = this.getTotalVertices();
  32090. if (!totalVertices || !this.getIndices()) {
  32091. return null;
  32092. }
  32093. // Check if we need to recreate the submeshes
  32094. if (this.subMeshes && this.subMeshes.length > 0) {
  32095. var ib = this.getIndices();
  32096. if (!ib) {
  32097. return null;
  32098. }
  32099. var totalIndices = ib.length;
  32100. var needToRecreate = false;
  32101. if (force) {
  32102. needToRecreate = true;
  32103. }
  32104. else {
  32105. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32106. var submesh = _a[_i];
  32107. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32108. needToRecreate = true;
  32109. break;
  32110. }
  32111. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32112. needToRecreate = true;
  32113. break;
  32114. }
  32115. }
  32116. }
  32117. if (!needToRecreate) {
  32118. return this.subMeshes[0];
  32119. }
  32120. }
  32121. this.releaseSubMeshes();
  32122. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32123. };
  32124. Mesh.prototype.subdivide = function (count) {
  32125. if (count < 1) {
  32126. return;
  32127. }
  32128. var totalIndices = this.getTotalIndices();
  32129. var subdivisionSize = (totalIndices / count) | 0;
  32130. var offset = 0;
  32131. // Ensure that subdivisionSize is a multiple of 3
  32132. while (subdivisionSize % 3 !== 0) {
  32133. subdivisionSize++;
  32134. }
  32135. this.releaseSubMeshes();
  32136. for (var index = 0; index < count; index++) {
  32137. if (offset >= totalIndices) {
  32138. break;
  32139. }
  32140. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32141. offset += subdivisionSize;
  32142. }
  32143. this.synchronizeInstances();
  32144. };
  32145. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32146. if (updatable === void 0) { updatable = false; }
  32147. if (!this._geometry) {
  32148. var vertexData = new BABYLON.VertexData();
  32149. vertexData.set(data, kind);
  32150. var scene = this.getScene();
  32151. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32152. }
  32153. else {
  32154. this._geometry.setVerticesData(kind, data, updatable, stride);
  32155. }
  32156. return this;
  32157. };
  32158. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32159. if (updatable === void 0) { updatable = true; }
  32160. var vb = this.getVertexBuffer(kind);
  32161. if (!vb || vb.isUpdatable() === updatable) {
  32162. return;
  32163. }
  32164. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32165. };
  32166. /**
  32167. * Sets the mesh VertexBuffer.
  32168. * Returns the Mesh.
  32169. */
  32170. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32171. if (!this._geometry) {
  32172. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32173. }
  32174. this._geometry.setVerticesBuffer(buffer);
  32175. return this;
  32176. };
  32177. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32178. if (!this._geometry) {
  32179. return this;
  32180. }
  32181. if (!makeItUnique) {
  32182. this._geometry.updateVerticesData(kind, data, updateExtends);
  32183. }
  32184. else {
  32185. this.makeGeometryUnique();
  32186. this.updateVerticesData(kind, data, updateExtends, false);
  32187. }
  32188. return this;
  32189. };
  32190. /**
  32191. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32192. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32193. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32194. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32195. * Returns the Mesh.
  32196. */
  32197. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32198. if (computeNormals === void 0) { computeNormals = true; }
  32199. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32200. if (!positions) {
  32201. return this;
  32202. }
  32203. positionFunction(positions);
  32204. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32205. if (computeNormals) {
  32206. var indices = this.getIndices();
  32207. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32208. if (!normals) {
  32209. return this;
  32210. }
  32211. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32212. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32213. }
  32214. return this;
  32215. };
  32216. /**
  32217. * Creates a un-shared specific occurence of the geometry for the mesh.
  32218. * Returns the Mesh.
  32219. */
  32220. Mesh.prototype.makeGeometryUnique = function () {
  32221. if (!this._geometry) {
  32222. return this;
  32223. }
  32224. var oldGeometry = this._geometry;
  32225. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32226. oldGeometry.releaseForMesh(this, true);
  32227. geometry.applyToMesh(this);
  32228. return this;
  32229. };
  32230. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32231. if (totalVertices === void 0) { totalVertices = null; }
  32232. if (updatable === void 0) { updatable = false; }
  32233. if (!this._geometry) {
  32234. var vertexData = new BABYLON.VertexData();
  32235. vertexData.indices = indices;
  32236. var scene = this.getScene();
  32237. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32238. }
  32239. else {
  32240. this._geometry.setIndices(indices, totalVertices, updatable);
  32241. }
  32242. return this;
  32243. };
  32244. /**
  32245. * Update the current index buffer
  32246. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32247. * Returns the Mesh.
  32248. */
  32249. Mesh.prototype.updateIndices = function (indices, offset) {
  32250. if (!this._geometry) {
  32251. return this;
  32252. }
  32253. this._geometry.updateIndices(indices, offset);
  32254. return this;
  32255. };
  32256. /**
  32257. * Invert the geometry to move from a right handed system to a left handed one.
  32258. * Returns the Mesh.
  32259. */
  32260. Mesh.prototype.toLeftHanded = function () {
  32261. if (!this._geometry) {
  32262. return this;
  32263. }
  32264. this._geometry.toLeftHanded();
  32265. return this;
  32266. };
  32267. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32268. if (!this._geometry) {
  32269. return this;
  32270. }
  32271. var engine = this.getScene().getEngine();
  32272. // Wireframe
  32273. var indexToBind;
  32274. if (this._unIndexed) {
  32275. indexToBind = null;
  32276. }
  32277. else {
  32278. switch (fillMode) {
  32279. case BABYLON.Material.PointFillMode:
  32280. indexToBind = null;
  32281. break;
  32282. case BABYLON.Material.WireFrameFillMode:
  32283. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32284. break;
  32285. default:
  32286. case BABYLON.Material.TriangleFillMode:
  32287. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32288. break;
  32289. }
  32290. }
  32291. // VBOs
  32292. this._geometry._bind(effect, indexToBind);
  32293. return this;
  32294. };
  32295. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32296. if (alternate === void 0) { alternate = false; }
  32297. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32298. return this;
  32299. }
  32300. this.onBeforeDrawObservable.notifyObservers(this);
  32301. var scene = this.getScene();
  32302. var engine = scene.getEngine();
  32303. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32304. // or triangles as points
  32305. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32306. }
  32307. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32308. // Triangles as wireframe
  32309. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32310. }
  32311. else {
  32312. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32313. }
  32314. if (scene._isAlternateRenderingEnabled && !alternate) {
  32315. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32316. if (!effect || !scene.activeCamera) {
  32317. return this;
  32318. }
  32319. scene._switchToAlternateCameraConfiguration(true);
  32320. this._effectiveMaterial.bindView(effect);
  32321. this._effectiveMaterial.bindViewProjection(effect);
  32322. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32323. this._draw(subMesh, fillMode, instancesCount, true);
  32324. engine.setViewport(scene.activeCamera.viewport);
  32325. scene._switchToAlternateCameraConfiguration(false);
  32326. this._effectiveMaterial.bindView(effect);
  32327. this._effectiveMaterial.bindViewProjection(effect);
  32328. }
  32329. return this;
  32330. };
  32331. /**
  32332. * Registers for this mesh a javascript function called just before the rendering process.
  32333. * This function is passed the current mesh.
  32334. * Return the Mesh.
  32335. */
  32336. Mesh.prototype.registerBeforeRender = function (func) {
  32337. this.onBeforeRenderObservable.add(func);
  32338. return this;
  32339. };
  32340. /**
  32341. * Disposes a previously registered javascript function called before the rendering.
  32342. * This function is passed the current mesh.
  32343. * Returns the Mesh.
  32344. */
  32345. Mesh.prototype.unregisterBeforeRender = function (func) {
  32346. this.onBeforeRenderObservable.removeCallback(func);
  32347. return this;
  32348. };
  32349. /**
  32350. * Registers for this mesh a javascript function called just after the rendering is complete.
  32351. * This function is passed the current mesh.
  32352. * Returns the Mesh.
  32353. */
  32354. Mesh.prototype.registerAfterRender = function (func) {
  32355. this.onAfterRenderObservable.add(func);
  32356. return this;
  32357. };
  32358. /**
  32359. * Disposes a previously registered javascript function called after the rendering.
  32360. * This function is passed the current mesh.
  32361. * Return the Mesh.
  32362. */
  32363. Mesh.prototype.unregisterAfterRender = function (func) {
  32364. this.onAfterRenderObservable.removeCallback(func);
  32365. return this;
  32366. };
  32367. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32368. var scene = this.getScene();
  32369. this._batchCache.mustReturn = false;
  32370. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32371. this._batchCache.visibleInstances[subMeshId] = null;
  32372. if (this._visibleInstances) {
  32373. var currentRenderId = scene.getRenderId();
  32374. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32375. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32376. var selfRenderId = this._renderId;
  32377. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32378. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32379. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32380. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32381. }
  32382. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32383. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32384. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32385. this._batchCache.mustReturn = true;
  32386. return this._batchCache;
  32387. }
  32388. if (currentRenderId !== selfRenderId) {
  32389. this._batchCache.renderSelf[subMeshId] = false;
  32390. }
  32391. }
  32392. this._renderIdForInstances[subMeshId] = currentRenderId;
  32393. }
  32394. return this._batchCache;
  32395. };
  32396. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32397. var visibleInstances = batch.visibleInstances[subMesh._id];
  32398. if (!visibleInstances) {
  32399. return this;
  32400. }
  32401. var matricesCount = visibleInstances.length + 1;
  32402. var bufferSize = matricesCount * 16 * 4;
  32403. var currentInstancesBufferSize = this._instancesBufferSize;
  32404. var instancesBuffer = this._instancesBuffer;
  32405. while (this._instancesBufferSize < bufferSize) {
  32406. this._instancesBufferSize *= 2;
  32407. }
  32408. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32409. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32410. }
  32411. var offset = 0;
  32412. var instancesCount = 0;
  32413. var world = this.getWorldMatrix();
  32414. if (batch.renderSelf[subMesh._id]) {
  32415. world.copyToArray(this._instancesData, offset);
  32416. offset += 16;
  32417. instancesCount++;
  32418. }
  32419. if (visibleInstances) {
  32420. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32421. var instance = visibleInstances[instanceIndex];
  32422. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32423. offset += 16;
  32424. instancesCount++;
  32425. }
  32426. }
  32427. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32428. if (instancesBuffer) {
  32429. instancesBuffer.dispose();
  32430. }
  32431. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32432. this._instancesBuffer = instancesBuffer;
  32433. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32434. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32435. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32436. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32437. }
  32438. else {
  32439. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32440. }
  32441. this._bind(subMesh, effect, fillMode);
  32442. this._draw(subMesh, fillMode, instancesCount);
  32443. engine.unbindInstanceAttributes();
  32444. return this;
  32445. };
  32446. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32447. var scene = this.getScene();
  32448. var engine = scene.getEngine();
  32449. if (hardwareInstancedRendering) {
  32450. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32451. }
  32452. else {
  32453. if (batch.renderSelf[subMesh._id]) {
  32454. // Draw
  32455. if (onBeforeDraw) {
  32456. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32457. }
  32458. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32459. }
  32460. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32461. if (visibleInstancesForSubMesh) {
  32462. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32463. var instance = visibleInstancesForSubMesh[instanceIndex];
  32464. // World
  32465. var world = instance.getWorldMatrix();
  32466. if (onBeforeDraw) {
  32467. onBeforeDraw(true, world, effectiveMaterial);
  32468. }
  32469. // Draw
  32470. this._draw(subMesh, fillMode);
  32471. }
  32472. }
  32473. }
  32474. return this;
  32475. };
  32476. /**
  32477. * Triggers the draw call for the mesh.
  32478. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32479. * Returns the Mesh.
  32480. */
  32481. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32482. this._checkOcclusionQuery();
  32483. if (this._isOccluded) {
  32484. return this;
  32485. }
  32486. var scene = this.getScene();
  32487. // Managing instances
  32488. var batch = this._getInstancesRenderList(subMesh._id);
  32489. if (batch.mustReturn) {
  32490. return this;
  32491. }
  32492. // Checking geometry state
  32493. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32494. return this;
  32495. }
  32496. this.onBeforeRenderObservable.notifyObservers(this);
  32497. var engine = scene.getEngine();
  32498. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32499. // Material
  32500. var material = subMesh.getMaterial();
  32501. if (!material) {
  32502. return this;
  32503. }
  32504. this._effectiveMaterial = material;
  32505. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32506. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32507. return this;
  32508. }
  32509. }
  32510. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32511. return this;
  32512. }
  32513. // Alpha mode
  32514. if (enableAlphaMode) {
  32515. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32516. }
  32517. // Outline - step 1
  32518. var savedDepthWrite = engine.getDepthWrite();
  32519. if (this.renderOutline) {
  32520. engine.setDepthWrite(false);
  32521. scene.getOutlineRenderer().render(subMesh, batch);
  32522. engine.setDepthWrite(savedDepthWrite);
  32523. }
  32524. var effect;
  32525. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32526. effect = subMesh.effect;
  32527. }
  32528. else {
  32529. effect = this._effectiveMaterial.getEffect();
  32530. }
  32531. if (!effect) {
  32532. return this;
  32533. }
  32534. var sideOrientation = this.overrideMaterialSideOrientation;
  32535. if (sideOrientation == null) {
  32536. sideOrientation = this._effectiveMaterial.sideOrientation;
  32537. if (this._getWorldMatrixDeterminant() < 0) {
  32538. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32539. }
  32540. }
  32541. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32542. if (this._effectiveMaterial.forceDepthWrite) {
  32543. engine.setDepthWrite(true);
  32544. }
  32545. // Bind
  32546. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32547. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32548. this._bind(subMesh, effect, fillMode);
  32549. }
  32550. var world = this.getWorldMatrix();
  32551. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32552. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32553. }
  32554. else {
  32555. this._effectiveMaterial.bind(world, this);
  32556. }
  32557. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32558. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32559. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32560. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32561. }
  32562. // Draw
  32563. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32564. // Unbind
  32565. this._effectiveMaterial.unbind();
  32566. // Outline - step 2
  32567. if (this.renderOutline && savedDepthWrite) {
  32568. engine.setDepthWrite(true);
  32569. engine.setColorWrite(false);
  32570. scene.getOutlineRenderer().render(subMesh, batch);
  32571. engine.setColorWrite(true);
  32572. }
  32573. // Overlay
  32574. if (this.renderOverlay) {
  32575. var currentMode = engine.getAlphaMode();
  32576. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32577. scene.getOutlineRenderer().render(subMesh, batch, true);
  32578. engine.setAlphaMode(currentMode);
  32579. }
  32580. this.onAfterRenderObservable.notifyObservers(this);
  32581. return this;
  32582. };
  32583. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32584. if (isInstance && effectiveMaterial) {
  32585. effectiveMaterial.bindOnlyWorldMatrix(world);
  32586. }
  32587. };
  32588. /**
  32589. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32590. */
  32591. Mesh.prototype.getEmittedParticleSystems = function () {
  32592. var results = new Array();
  32593. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32594. var particleSystem = this.getScene().particleSystems[index];
  32595. if (particleSystem.emitter === this) {
  32596. results.push(particleSystem);
  32597. }
  32598. }
  32599. return results;
  32600. };
  32601. /**
  32602. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32603. */
  32604. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32605. var results = new Array();
  32606. var descendants = this.getDescendants();
  32607. descendants.push(this);
  32608. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32609. var particleSystem = this.getScene().particleSystems[index];
  32610. var emitter = particleSystem.emitter;
  32611. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32612. results.push(particleSystem);
  32613. }
  32614. }
  32615. return results;
  32616. };
  32617. /**
  32618. * Normalize matrix weights so that all vertices have a total weight set to 1
  32619. */
  32620. Mesh.prototype.cleanMatrixWeights = function () {
  32621. var epsilon = 1e-3;
  32622. var noInfluenceBoneIndex = 0.0;
  32623. if (this.skeleton) {
  32624. noInfluenceBoneIndex = this.skeleton.bones.length;
  32625. }
  32626. else {
  32627. return;
  32628. }
  32629. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32630. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32631. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32632. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32633. var influencers = this.numBoneInfluencers;
  32634. var size = matricesWeights.length;
  32635. for (var i = 0; i < size; i += 4) {
  32636. var weight = 0.0;
  32637. var firstZeroWeight = -1;
  32638. for (var j = 0; j < 4; j++) {
  32639. var w = matricesWeights[i + j];
  32640. weight += w;
  32641. if (w < epsilon && firstZeroWeight < 0) {
  32642. firstZeroWeight = j;
  32643. }
  32644. }
  32645. if (matricesWeightsExtra) {
  32646. for (var j = 0; j < 4; j++) {
  32647. var w = matricesWeightsExtra[i + j];
  32648. weight += w;
  32649. if (w < epsilon && firstZeroWeight < 0) {
  32650. firstZeroWeight = j + 4;
  32651. }
  32652. }
  32653. }
  32654. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32655. firstZeroWeight = influencers - 1;
  32656. }
  32657. if (weight > epsilon) {
  32658. var mweight = 1.0 / weight;
  32659. for (var j = 0; j < 4; j++) {
  32660. matricesWeights[i + j] *= mweight;
  32661. }
  32662. if (matricesWeightsExtra) {
  32663. for (var j = 0; j < 4; j++) {
  32664. matricesWeightsExtra[i + j] *= mweight;
  32665. }
  32666. }
  32667. }
  32668. else {
  32669. if (firstZeroWeight >= 4) {
  32670. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32671. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32672. }
  32673. else {
  32674. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32675. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32676. }
  32677. }
  32678. }
  32679. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32680. if (matricesIndicesExtra) {
  32681. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32682. }
  32683. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32684. if (matricesWeightsExtra) {
  32685. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32686. }
  32687. };
  32688. Mesh.prototype._checkDelayState = function () {
  32689. var scene = this.getScene();
  32690. if (this._geometry) {
  32691. this._geometry.load(scene);
  32692. }
  32693. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32695. this._queueLoad(scene);
  32696. }
  32697. return this;
  32698. };
  32699. Mesh.prototype._queueLoad = function (scene) {
  32700. var _this = this;
  32701. scene._addPendingData(this);
  32702. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32703. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32704. if (data instanceof ArrayBuffer) {
  32705. _this._delayLoadingFunction(data, _this);
  32706. }
  32707. else {
  32708. _this._delayLoadingFunction(JSON.parse(data), _this);
  32709. }
  32710. _this.instances.forEach(function (instance) {
  32711. instance._syncSubMeshes();
  32712. });
  32713. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32714. scene._removePendingData(_this);
  32715. }, function () { }, scene.database, getBinaryData);
  32716. return this;
  32717. };
  32718. /**
  32719. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32720. */
  32721. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32722. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32723. return false;
  32724. }
  32725. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32726. return false;
  32727. }
  32728. this._checkDelayState();
  32729. return true;
  32730. };
  32731. /**
  32732. * Sets the mesh material by the material or multiMaterial `id` property.
  32733. * The material `id` is a string identifying the material or the multiMaterial.
  32734. * This method returns the Mesh.
  32735. */
  32736. Mesh.prototype.setMaterialByID = function (id) {
  32737. var materials = this.getScene().materials;
  32738. var index;
  32739. for (index = materials.length - 1; index > -1; index--) {
  32740. if (materials[index].id === id) {
  32741. this.material = materials[index];
  32742. return this;
  32743. }
  32744. }
  32745. // Multi
  32746. var multiMaterials = this.getScene().multiMaterials;
  32747. for (index = multiMaterials.length - 1; index > -1; index--) {
  32748. if (multiMaterials[index].id === id) {
  32749. this.material = multiMaterials[index];
  32750. return this;
  32751. }
  32752. }
  32753. return this;
  32754. };
  32755. /**
  32756. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32757. */
  32758. Mesh.prototype.getAnimatables = function () {
  32759. var results = new Array();
  32760. if (this.material) {
  32761. results.push(this.material);
  32762. }
  32763. if (this.skeleton) {
  32764. results.push(this.skeleton);
  32765. }
  32766. return results;
  32767. };
  32768. /**
  32769. * Modifies the mesh geometry according to the passed transformation matrix.
  32770. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32771. * The mesh normals are modified accordingly the same transformation.
  32772. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32773. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32774. * Returns the Mesh.
  32775. */
  32776. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32777. // Position
  32778. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32779. return this;
  32780. }
  32781. var submeshes = this.subMeshes.splice(0);
  32782. this._resetPointsArrayCache();
  32783. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32784. var temp = new Array();
  32785. var index;
  32786. for (index = 0; index < data.length; index += 3) {
  32787. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32788. }
  32789. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32790. // Normals
  32791. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32792. return this;
  32793. }
  32794. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32795. temp = [];
  32796. for (index = 0; index < data.length; index += 3) {
  32797. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32798. }
  32799. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32800. // flip faces?
  32801. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32802. this.flipFaces();
  32803. }
  32804. // Restore submeshes
  32805. this.releaseSubMeshes();
  32806. this.subMeshes = submeshes;
  32807. return this;
  32808. };
  32809. /**
  32810. * Modifies the mesh geometry according to its own current World Matrix.
  32811. * The mesh World Matrix is then reset.
  32812. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32813. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32814. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32815. * Returns the Mesh.
  32816. */
  32817. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32818. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32819. this.scaling.copyFromFloats(1, 1, 1);
  32820. this.position.copyFromFloats(0, 0, 0);
  32821. this.rotation.copyFromFloats(0, 0, 0);
  32822. //only if quaternion is already set
  32823. if (this.rotationQuaternion) {
  32824. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32825. }
  32826. this._worldMatrix = BABYLON.Matrix.Identity();
  32827. return this;
  32828. };
  32829. Object.defineProperty(Mesh.prototype, "_positions", {
  32830. // Cache
  32831. get: function () {
  32832. if (this._geometry) {
  32833. return this._geometry._positions;
  32834. }
  32835. return null;
  32836. },
  32837. enumerable: true,
  32838. configurable: true
  32839. });
  32840. Mesh.prototype._resetPointsArrayCache = function () {
  32841. if (this._geometry) {
  32842. this._geometry._resetPointsArrayCache();
  32843. }
  32844. return this;
  32845. };
  32846. Mesh.prototype._generatePointsArray = function () {
  32847. if (this._geometry) {
  32848. return this._geometry._generatePointsArray();
  32849. }
  32850. return false;
  32851. };
  32852. /**
  32853. * Returns a new Mesh object generated from the current mesh properties.
  32854. * This method must not get confused with createInstance().
  32855. * The parameter `name` is a string, the name given to the new mesh.
  32856. * The optional parameter `newParent` can be any Node object (default `null`).
  32857. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32858. * 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.
  32859. */
  32860. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32861. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32862. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32863. };
  32864. /**
  32865. * Releases resources associated with this mesh.
  32866. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32867. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32868. */
  32869. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32870. var _this = this;
  32871. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32872. this.morphTargetManager = null;
  32873. if (this._geometry) {
  32874. this._geometry.releaseForMesh(this, true);
  32875. }
  32876. // Sources
  32877. var meshes = this.getScene().meshes;
  32878. meshes.forEach(function (abstractMesh) {
  32879. var mesh = abstractMesh;
  32880. if (mesh._source && mesh._source === _this) {
  32881. mesh._source = null;
  32882. }
  32883. });
  32884. this._source = null;
  32885. // Instances
  32886. if (this._instancesBuffer) {
  32887. this._instancesBuffer.dispose();
  32888. this._instancesBuffer = null;
  32889. }
  32890. while (this.instances.length) {
  32891. this.instances[0].dispose();
  32892. }
  32893. // Effect layers.
  32894. var effectLayers = this.getScene().effectLayers;
  32895. for (var i = 0; i < effectLayers.length; i++) {
  32896. var effectLayer = effectLayers[i];
  32897. if (effectLayer) {
  32898. effectLayer._disposeMesh(this);
  32899. }
  32900. }
  32901. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32902. };
  32903. /**
  32904. * Modifies the mesh geometry according to a displacement map.
  32905. * 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.
  32906. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32907. * This method returns nothing.
  32908. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32909. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32910. * 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.
  32911. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32912. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32913. *
  32914. * Returns the Mesh.
  32915. */
  32916. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32917. var _this = this;
  32918. var scene = this.getScene();
  32919. var onload = function (img) {
  32920. // Getting height map data
  32921. var canvas = document.createElement("canvas");
  32922. var context = canvas.getContext("2d");
  32923. var heightMapWidth = img.width;
  32924. var heightMapHeight = img.height;
  32925. canvas.width = heightMapWidth;
  32926. canvas.height = heightMapHeight;
  32927. context.drawImage(img, 0, 0);
  32928. // Create VertexData from map data
  32929. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32930. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32931. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32932. //execute success callback, if set
  32933. if (onSuccess) {
  32934. onSuccess(_this);
  32935. }
  32936. };
  32937. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32938. return this;
  32939. };
  32940. /**
  32941. * Modifies the mesh geometry according to a displacementMap buffer.
  32942. * 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.
  32943. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32944. * This method returns nothing.
  32945. * 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.
  32946. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32947. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32948. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32949. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32950. *
  32951. * Returns the Mesh.
  32952. */
  32953. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32954. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32955. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32956. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32957. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32958. return this;
  32959. }
  32960. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32961. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32962. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32963. var position = BABYLON.Vector3.Zero();
  32964. var normal = BABYLON.Vector3.Zero();
  32965. var uv = BABYLON.Vector2.Zero();
  32966. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32967. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32968. for (var index = 0; index < positions.length; index += 3) {
  32969. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32970. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32971. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32972. // Compute height
  32973. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32974. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32975. var pos = (u + v * heightMapWidth) * 4;
  32976. var r = buffer[pos] / 255.0;
  32977. var g = buffer[pos + 1] / 255.0;
  32978. var b = buffer[pos + 2] / 255.0;
  32979. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32980. normal.normalize();
  32981. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32982. position = position.add(normal);
  32983. position.toArray(positions, index);
  32984. }
  32985. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32986. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32987. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32988. return this;
  32989. };
  32990. /**
  32991. * Modify the mesh to get a flat shading rendering.
  32992. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32993. * This method returns the Mesh.
  32994. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32995. */
  32996. Mesh.prototype.convertToFlatShadedMesh = function () {
  32997. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32998. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32999. var kinds = this.getVerticesDataKinds();
  33000. var vbs = {};
  33001. var data = {};
  33002. var newdata = {};
  33003. var updatableNormals = false;
  33004. var kindIndex;
  33005. var kind;
  33006. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33007. kind = kinds[kindIndex];
  33008. var vertexBuffer = this.getVertexBuffer(kind);
  33009. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33010. updatableNormals = vertexBuffer.isUpdatable();
  33011. kinds.splice(kindIndex, 1);
  33012. kindIndex--;
  33013. continue;
  33014. }
  33015. vbs[kind] = vertexBuffer;
  33016. data[kind] = vbs[kind].getData();
  33017. newdata[kind] = [];
  33018. }
  33019. // Save previous submeshes
  33020. var previousSubmeshes = this.subMeshes.slice(0);
  33021. var indices = this.getIndices();
  33022. var totalIndices = this.getTotalIndices();
  33023. // Generating unique vertices per face
  33024. var index;
  33025. for (index = 0; index < totalIndices; index++) {
  33026. var vertexIndex = indices[index];
  33027. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33028. kind = kinds[kindIndex];
  33029. var stride = vbs[kind].getStrideSize();
  33030. for (var offset = 0; offset < stride; offset++) {
  33031. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33032. }
  33033. }
  33034. }
  33035. // Updating faces & normal
  33036. var normals = [];
  33037. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33038. for (index = 0; index < totalIndices; index += 3) {
  33039. indices[index] = index;
  33040. indices[index + 1] = index + 1;
  33041. indices[index + 2] = index + 2;
  33042. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33043. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33044. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33045. var p1p2 = p1.subtract(p2);
  33046. var p3p2 = p3.subtract(p2);
  33047. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33048. // Store same normals for every vertex
  33049. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33050. normals.push(normal.x);
  33051. normals.push(normal.y);
  33052. normals.push(normal.z);
  33053. }
  33054. }
  33055. this.setIndices(indices);
  33056. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33057. // Updating vertex buffers
  33058. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33059. kind = kinds[kindIndex];
  33060. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33061. }
  33062. // Updating submeshes
  33063. this.releaseSubMeshes();
  33064. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33065. var previousOne = previousSubmeshes[submeshIndex];
  33066. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33067. }
  33068. this.synchronizeInstances();
  33069. return this;
  33070. };
  33071. /**
  33072. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33073. * In other words, more vertices, no more indices and a single bigger VBO.
  33074. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33075. * Returns the Mesh.
  33076. */
  33077. Mesh.prototype.convertToUnIndexedMesh = function () {
  33078. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33079. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33080. var kinds = this.getVerticesDataKinds();
  33081. var vbs = {};
  33082. var data = {};
  33083. var newdata = {};
  33084. var kindIndex;
  33085. var kind;
  33086. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33087. kind = kinds[kindIndex];
  33088. var vertexBuffer = this.getVertexBuffer(kind);
  33089. vbs[kind] = vertexBuffer;
  33090. data[kind] = vbs[kind].getData();
  33091. newdata[kind] = [];
  33092. }
  33093. // Save previous submeshes
  33094. var previousSubmeshes = this.subMeshes.slice(0);
  33095. var indices = this.getIndices();
  33096. var totalIndices = this.getTotalIndices();
  33097. // Generating unique vertices per face
  33098. var index;
  33099. for (index = 0; index < totalIndices; index++) {
  33100. var vertexIndex = indices[index];
  33101. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33102. kind = kinds[kindIndex];
  33103. var stride = vbs[kind].getStrideSize();
  33104. for (var offset = 0; offset < stride; offset++) {
  33105. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33106. }
  33107. }
  33108. }
  33109. // Updating indices
  33110. for (index = 0; index < totalIndices; index += 3) {
  33111. indices[index] = index;
  33112. indices[index + 1] = index + 1;
  33113. indices[index + 2] = index + 2;
  33114. }
  33115. this.setIndices(indices);
  33116. // Updating vertex buffers
  33117. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33118. kind = kinds[kindIndex];
  33119. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33120. }
  33121. // Updating submeshes
  33122. this.releaseSubMeshes();
  33123. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33124. var previousOne = previousSubmeshes[submeshIndex];
  33125. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33126. }
  33127. this._unIndexed = true;
  33128. this.synchronizeInstances();
  33129. return this;
  33130. };
  33131. /**
  33132. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33133. * This method returns the Mesh.
  33134. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33135. */
  33136. Mesh.prototype.flipFaces = function (flipNormals) {
  33137. if (flipNormals === void 0) { flipNormals = false; }
  33138. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33139. var i;
  33140. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33141. for (i = 0; i < vertex_data.normals.length; i++) {
  33142. vertex_data.normals[i] *= -1;
  33143. }
  33144. }
  33145. if (vertex_data.indices) {
  33146. var temp;
  33147. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33148. // reassign indices
  33149. temp = vertex_data.indices[i + 1];
  33150. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33151. vertex_data.indices[i + 2] = temp;
  33152. }
  33153. }
  33154. vertex_data.applyToMesh(this);
  33155. return this;
  33156. };
  33157. // Instances
  33158. /**
  33159. * Creates a new InstancedMesh object from the mesh model.
  33160. * An instance shares the same properties and the same material than its model.
  33161. * Only these properties of each instance can then be set individually :
  33162. * - position
  33163. * - rotation
  33164. * - rotationQuaternion
  33165. * - setPivotMatrix
  33166. * - scaling
  33167. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33168. * Warning : this method is not supported for Line mesh and LineSystem
  33169. */
  33170. Mesh.prototype.createInstance = function (name) {
  33171. return new BABYLON.InstancedMesh(name, this);
  33172. };
  33173. /**
  33174. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33175. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33176. * This method returns the Mesh.
  33177. */
  33178. Mesh.prototype.synchronizeInstances = function () {
  33179. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33180. var instance = this.instances[instanceIndex];
  33181. instance._syncSubMeshes();
  33182. }
  33183. return this;
  33184. };
  33185. /**
  33186. * Simplify the mesh according to the given array of settings.
  33187. * Function will return immediately and will simplify async. It returns the Mesh.
  33188. * @param settings a collection of simplification settings.
  33189. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33190. * @param type the type of simplification to run.
  33191. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33192. */
  33193. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33194. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33195. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33196. this.getScene().simplificationQueue.addTask({
  33197. settings: settings,
  33198. parallelProcessing: parallelProcessing,
  33199. mesh: this,
  33200. simplificationType: simplificationType,
  33201. successCallback: successCallback
  33202. });
  33203. return this;
  33204. };
  33205. /**
  33206. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33207. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33208. * This should be used together with the simplification to avoid disappearing triangles.
  33209. * Returns the Mesh.
  33210. * @param successCallback an optional success callback to be called after the optimization finished.
  33211. */
  33212. Mesh.prototype.optimizeIndices = function (successCallback) {
  33213. var _this = this;
  33214. var indices = this.getIndices();
  33215. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33216. if (!positions || !indices) {
  33217. return this;
  33218. }
  33219. var vectorPositions = new Array();
  33220. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33221. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33222. }
  33223. var dupes = new Array();
  33224. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33225. var realPos = vectorPositions.length - 1 - iteration;
  33226. var testedPosition = vectorPositions[realPos];
  33227. for (var j = 0; j < realPos; ++j) {
  33228. var againstPosition = vectorPositions[j];
  33229. if (testedPosition.equals(againstPosition)) {
  33230. dupes[realPos] = j;
  33231. break;
  33232. }
  33233. }
  33234. }, function () {
  33235. for (var i = 0; i < indices.length; ++i) {
  33236. indices[i] = dupes[indices[i]] || indices[i];
  33237. }
  33238. //indices are now reordered
  33239. var originalSubMeshes = _this.subMeshes.slice(0);
  33240. _this.setIndices(indices);
  33241. _this.subMeshes = originalSubMeshes;
  33242. if (successCallback) {
  33243. successCallback(_this);
  33244. }
  33245. });
  33246. return this;
  33247. };
  33248. Mesh.prototype.serialize = function (serializationObject) {
  33249. serializationObject.name = this.name;
  33250. serializationObject.id = this.id;
  33251. serializationObject.type = this.getClassName();
  33252. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33253. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33254. }
  33255. serializationObject.position = this.position.asArray();
  33256. if (this.rotationQuaternion) {
  33257. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33258. }
  33259. else if (this.rotation) {
  33260. serializationObject.rotation = this.rotation.asArray();
  33261. }
  33262. serializationObject.scaling = this.scaling.asArray();
  33263. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33264. serializationObject.isEnabled = this.isEnabled(false);
  33265. serializationObject.isVisible = this.isVisible;
  33266. serializationObject.infiniteDistance = this.infiniteDistance;
  33267. serializationObject.pickable = this.isPickable;
  33268. serializationObject.receiveShadows = this.receiveShadows;
  33269. serializationObject.billboardMode = this.billboardMode;
  33270. serializationObject.visibility = this.visibility;
  33271. serializationObject.checkCollisions = this.checkCollisions;
  33272. serializationObject.isBlocker = this.isBlocker;
  33273. // Parent
  33274. if (this.parent) {
  33275. serializationObject.parentId = this.parent.id;
  33276. }
  33277. // Geometry
  33278. serializationObject.isUnIndexed = this.isUnIndexed;
  33279. var geometry = this._geometry;
  33280. if (geometry) {
  33281. var geometryId = geometry.id;
  33282. serializationObject.geometryId = geometryId;
  33283. // SubMeshes
  33284. serializationObject.subMeshes = [];
  33285. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33286. var subMesh = this.subMeshes[subIndex];
  33287. serializationObject.subMeshes.push({
  33288. materialIndex: subMesh.materialIndex,
  33289. verticesStart: subMesh.verticesStart,
  33290. verticesCount: subMesh.verticesCount,
  33291. indexStart: subMesh.indexStart,
  33292. indexCount: subMesh.indexCount
  33293. });
  33294. }
  33295. }
  33296. // Material
  33297. if (this.material) {
  33298. serializationObject.materialId = this.material.id;
  33299. }
  33300. else {
  33301. this.material = null;
  33302. }
  33303. // Morph targets
  33304. if (this.morphTargetManager) {
  33305. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33306. }
  33307. // Skeleton
  33308. if (this.skeleton) {
  33309. serializationObject.skeletonId = this.skeleton.id;
  33310. }
  33311. // Physics
  33312. //TODO implement correct serialization for physics impostors.
  33313. var impostor = this.getPhysicsImpostor();
  33314. if (impostor) {
  33315. serializationObject.physicsMass = impostor.getParam("mass");
  33316. serializationObject.physicsFriction = impostor.getParam("friction");
  33317. serializationObject.physicsRestitution = impostor.getParam("mass");
  33318. serializationObject.physicsImpostor = impostor.type;
  33319. }
  33320. // Metadata
  33321. if (this.metadata) {
  33322. serializationObject.metadata = this.metadata;
  33323. }
  33324. // Instances
  33325. serializationObject.instances = [];
  33326. for (var index = 0; index < this.instances.length; index++) {
  33327. var instance = this.instances[index];
  33328. var serializationInstance = {
  33329. name: instance.name,
  33330. id: instance.id,
  33331. position: instance.position.asArray(),
  33332. scaling: instance.scaling.asArray()
  33333. };
  33334. if (instance.rotationQuaternion) {
  33335. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33336. }
  33337. else if (instance.rotation) {
  33338. serializationInstance.rotation = instance.rotation.asArray();
  33339. }
  33340. serializationObject.instances.push(serializationInstance);
  33341. // Animations
  33342. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33343. serializationInstance.ranges = instance.serializeAnimationRanges();
  33344. }
  33345. //
  33346. // Animations
  33347. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33348. serializationObject.ranges = this.serializeAnimationRanges();
  33349. // Layer mask
  33350. serializationObject.layerMask = this.layerMask;
  33351. // Alpha
  33352. serializationObject.alphaIndex = this.alphaIndex;
  33353. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33354. // Overlay
  33355. serializationObject.overlayAlpha = this.overlayAlpha;
  33356. serializationObject.overlayColor = this.overlayColor.asArray();
  33357. serializationObject.renderOverlay = this.renderOverlay;
  33358. // Fog
  33359. serializationObject.applyFog = this.applyFog;
  33360. // Action Manager
  33361. if (this.actionManager) {
  33362. serializationObject.actions = this.actionManager.serialize(this.name);
  33363. }
  33364. };
  33365. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33366. if (!this.geometry) {
  33367. return;
  33368. }
  33369. this._markSubMeshesAsAttributesDirty();
  33370. var morphTargetManager = this._morphTargetManager;
  33371. if (morphTargetManager && morphTargetManager.vertexCount) {
  33372. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33373. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33374. this.morphTargetManager = null;
  33375. return;
  33376. }
  33377. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33378. var morphTarget = morphTargetManager.getActiveTarget(index);
  33379. var positions = morphTarget.getPositions();
  33380. if (!positions) {
  33381. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33382. return;
  33383. }
  33384. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33385. var normals = morphTarget.getNormals();
  33386. if (normals) {
  33387. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33388. }
  33389. var tangents = morphTarget.getTangents();
  33390. if (tangents) {
  33391. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33392. }
  33393. }
  33394. }
  33395. else {
  33396. var index = 0;
  33397. // Positions
  33398. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33399. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33400. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33401. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33402. }
  33403. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33404. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33405. }
  33406. index++;
  33407. }
  33408. }
  33409. };
  33410. // Statics
  33411. /**
  33412. * Returns a new Mesh object parsed from the source provided.
  33413. * The parameter `parsedMesh` is the source.
  33414. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33415. */
  33416. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33417. var mesh;
  33418. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33419. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33420. }
  33421. else {
  33422. mesh = new Mesh(parsedMesh.name, scene);
  33423. }
  33424. mesh.id = parsedMesh.id;
  33425. if (BABYLON.Tags) {
  33426. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33427. }
  33428. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33429. if (parsedMesh.metadata !== undefined) {
  33430. mesh.metadata = parsedMesh.metadata;
  33431. }
  33432. if (parsedMesh.rotationQuaternion) {
  33433. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33434. }
  33435. else if (parsedMesh.rotation) {
  33436. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33437. }
  33438. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33439. if (parsedMesh.localMatrix) {
  33440. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33441. }
  33442. else if (parsedMesh.pivotMatrix) {
  33443. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33444. }
  33445. mesh.setEnabled(parsedMesh.isEnabled);
  33446. mesh.isVisible = parsedMesh.isVisible;
  33447. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33448. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33449. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33450. if (parsedMesh.applyFog !== undefined) {
  33451. mesh.applyFog = parsedMesh.applyFog;
  33452. }
  33453. if (parsedMesh.pickable !== undefined) {
  33454. mesh.isPickable = parsedMesh.pickable;
  33455. }
  33456. if (parsedMesh.alphaIndex !== undefined) {
  33457. mesh.alphaIndex = parsedMesh.alphaIndex;
  33458. }
  33459. mesh.receiveShadows = parsedMesh.receiveShadows;
  33460. mesh.billboardMode = parsedMesh.billboardMode;
  33461. if (parsedMesh.visibility !== undefined) {
  33462. mesh.visibility = parsedMesh.visibility;
  33463. }
  33464. mesh.checkCollisions = parsedMesh.checkCollisions;
  33465. if (parsedMesh.isBlocker !== undefined) {
  33466. mesh.isBlocker = parsedMesh.isBlocker;
  33467. }
  33468. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33469. // freezeWorldMatrix
  33470. if (parsedMesh.freezeWorldMatrix) {
  33471. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33472. }
  33473. // Parent
  33474. if (parsedMesh.parentId) {
  33475. mesh._waitingParentId = parsedMesh.parentId;
  33476. }
  33477. // Actions
  33478. if (parsedMesh.actions !== undefined) {
  33479. mesh._waitingActions = parsedMesh.actions;
  33480. }
  33481. // Overlay
  33482. if (parsedMesh.overlayAlpha !== undefined) {
  33483. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33484. }
  33485. if (parsedMesh.overlayColor !== undefined) {
  33486. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33487. }
  33488. if (parsedMesh.renderOverlay !== undefined) {
  33489. mesh.renderOverlay = parsedMesh.renderOverlay;
  33490. }
  33491. // Geometry
  33492. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33493. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33494. if (parsedMesh.delayLoadingFile) {
  33495. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33496. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33497. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33498. if (parsedMesh._binaryInfo) {
  33499. mesh._binaryInfo = parsedMesh._binaryInfo;
  33500. }
  33501. mesh._delayInfo = [];
  33502. if (parsedMesh.hasUVs) {
  33503. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33504. }
  33505. if (parsedMesh.hasUVs2) {
  33506. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33507. }
  33508. if (parsedMesh.hasUVs3) {
  33509. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33510. }
  33511. if (parsedMesh.hasUVs4) {
  33512. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33513. }
  33514. if (parsedMesh.hasUVs5) {
  33515. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33516. }
  33517. if (parsedMesh.hasUVs6) {
  33518. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33519. }
  33520. if (parsedMesh.hasColors) {
  33521. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33522. }
  33523. if (parsedMesh.hasMatricesIndices) {
  33524. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33525. }
  33526. if (parsedMesh.hasMatricesWeights) {
  33527. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33528. }
  33529. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33530. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33531. mesh._checkDelayState();
  33532. }
  33533. }
  33534. else {
  33535. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33536. }
  33537. // Material
  33538. if (parsedMesh.materialId) {
  33539. mesh.setMaterialByID(parsedMesh.materialId);
  33540. }
  33541. else {
  33542. mesh.material = null;
  33543. }
  33544. // Morph targets
  33545. if (parsedMesh.morphTargetManagerId > -1) {
  33546. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33547. }
  33548. // Skeleton
  33549. if (parsedMesh.skeletonId > -1) {
  33550. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33551. if (parsedMesh.numBoneInfluencers) {
  33552. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33553. }
  33554. }
  33555. // Animations
  33556. if (parsedMesh.animations) {
  33557. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33558. var parsedAnimation = parsedMesh.animations[animationIndex];
  33559. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33560. }
  33561. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33562. }
  33563. if (parsedMesh.autoAnimate) {
  33564. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33565. }
  33566. // Layer Mask
  33567. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33568. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33569. }
  33570. else {
  33571. mesh.layerMask = 0x0FFFFFFF;
  33572. }
  33573. // Physics
  33574. if (parsedMesh.physicsImpostor) {
  33575. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33576. mass: parsedMesh.physicsMass,
  33577. friction: parsedMesh.physicsFriction,
  33578. restitution: parsedMesh.physicsRestitution
  33579. }, scene);
  33580. }
  33581. // Instances
  33582. if (parsedMesh.instances) {
  33583. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33584. var parsedInstance = parsedMesh.instances[index];
  33585. var instance = mesh.createInstance(parsedInstance.name);
  33586. if (parsedInstance.id) {
  33587. instance.id = parsedInstance.id;
  33588. }
  33589. if (BABYLON.Tags) {
  33590. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33591. }
  33592. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33593. if (parsedInstance.parentId) {
  33594. instance._waitingParentId = parsedInstance.parentId;
  33595. }
  33596. if (parsedInstance.rotationQuaternion) {
  33597. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33598. }
  33599. else if (parsedInstance.rotation) {
  33600. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33601. }
  33602. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33603. instance.checkCollisions = mesh.checkCollisions;
  33604. if (parsedMesh.animations) {
  33605. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33606. parsedAnimation = parsedMesh.animations[animationIndex];
  33607. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33608. }
  33609. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33610. }
  33611. }
  33612. }
  33613. return mesh;
  33614. };
  33615. /**
  33616. * Creates a ribbon mesh.
  33617. * Please consider using the same method from the MeshBuilder class instead.
  33618. * 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.
  33619. *
  33620. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33621. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33622. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33623. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33624. * 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.
  33625. * 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.
  33626. * 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
  33627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33628. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33630. */
  33631. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33632. if (closeArray === void 0) { closeArray = false; }
  33633. if (updatable === void 0) { updatable = false; }
  33634. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33635. pathArray: pathArray,
  33636. closeArray: closeArray,
  33637. closePath: closePath,
  33638. offset: offset,
  33639. updatable: updatable,
  33640. sideOrientation: sideOrientation,
  33641. instance: instance
  33642. }, scene);
  33643. };
  33644. /**
  33645. * Creates a plane polygonal mesh. By default, this is a disc.
  33646. * Please consider using the same method from the MeshBuilder class instead.
  33647. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33648. * 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.
  33649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33650. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33652. */
  33653. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33654. if (scene === void 0) { scene = null; }
  33655. var options = {
  33656. radius: radius,
  33657. tessellation: tessellation,
  33658. sideOrientation: sideOrientation,
  33659. updatable: updatable
  33660. };
  33661. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33662. };
  33663. /**
  33664. * Creates a box mesh.
  33665. * Please consider using the same method from the MeshBuilder class instead.
  33666. * The parameter `size` sets the size (float) of each box side (default 1).
  33667. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33668. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33670. */
  33671. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33672. if (scene === void 0) { scene = null; }
  33673. var options = {
  33674. size: size,
  33675. sideOrientation: sideOrientation,
  33676. updatable: updatable
  33677. };
  33678. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33679. };
  33680. /**
  33681. * Creates a sphere mesh.
  33682. * Please consider using the same method from the MeshBuilder class instead.
  33683. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33684. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33685. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33686. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33687. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33688. */
  33689. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33690. var options = {
  33691. segments: segments,
  33692. diameterX: diameter,
  33693. diameterY: diameter,
  33694. diameterZ: diameter,
  33695. sideOrientation: sideOrientation,
  33696. updatable: updatable
  33697. };
  33698. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33699. };
  33700. /**
  33701. * Creates a cylinder or a cone mesh.
  33702. * Please consider using the same method from the MeshBuilder class instead.
  33703. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33704. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33705. * 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.
  33706. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33707. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33708. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33709. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33711. */
  33712. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33713. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33714. if (scene !== undefined) {
  33715. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33716. updatable = scene;
  33717. }
  33718. scene = subdivisions;
  33719. subdivisions = 1;
  33720. }
  33721. var options = {
  33722. height: height,
  33723. diameterTop: diameterTop,
  33724. diameterBottom: diameterBottom,
  33725. tessellation: tessellation,
  33726. subdivisions: subdivisions,
  33727. sideOrientation: sideOrientation,
  33728. updatable: updatable
  33729. };
  33730. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33731. };
  33732. // Torus (Code from SharpDX.org)
  33733. /**
  33734. * Creates a torus mesh.
  33735. * Please consider using the same method from the MeshBuilder class instead.
  33736. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33737. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33738. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33739. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33740. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33741. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33742. */
  33743. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33744. var options = {
  33745. diameter: diameter,
  33746. thickness: thickness,
  33747. tessellation: tessellation,
  33748. sideOrientation: sideOrientation,
  33749. updatable: updatable
  33750. };
  33751. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33752. };
  33753. /**
  33754. * Creates a torus knot mesh.
  33755. * Please consider using the same method from the MeshBuilder class instead.
  33756. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33757. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33758. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33759. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33760. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33761. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33762. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33763. */
  33764. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33765. var options = {
  33766. radius: radius,
  33767. tube: tube,
  33768. radialSegments: radialSegments,
  33769. tubularSegments: tubularSegments,
  33770. p: p,
  33771. q: q,
  33772. sideOrientation: sideOrientation,
  33773. updatable: updatable
  33774. };
  33775. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33776. };
  33777. /**
  33778. * Creates a line mesh.
  33779. * Please consider using the same method from the MeshBuilder class instead.
  33780. * 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.
  33781. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33782. * The parameter `points` is an array successive Vector3.
  33783. * 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
  33784. * When updating an instance, remember that only point positions can change, not the number of points.
  33785. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33786. */
  33787. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33788. if (scene === void 0) { scene = null; }
  33789. if (updatable === void 0) { updatable = false; }
  33790. if (instance === void 0) { instance = null; }
  33791. var options = {
  33792. points: points,
  33793. updatable: updatable,
  33794. instance: instance
  33795. };
  33796. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33797. };
  33798. /**
  33799. * Creates a dashed line mesh.
  33800. * Please consider using the same method from the MeshBuilder class instead.
  33801. * 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.
  33802. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33803. * The parameter `points` is an array successive Vector3.
  33804. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33805. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33806. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33807. * 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
  33808. * When updating an instance, remember that only point positions can change, not the number of points.
  33809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33810. */
  33811. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33812. if (scene === void 0) { scene = null; }
  33813. var options = {
  33814. points: points,
  33815. dashSize: dashSize,
  33816. gapSize: gapSize,
  33817. dashNb: dashNb,
  33818. updatable: updatable,
  33819. instance: instance
  33820. };
  33821. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33822. };
  33823. /**
  33824. * Creates a polygon mesh.
  33825. * Please consider using the same method from the MeshBuilder class instead.
  33826. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33827. * 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.
  33828. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33830. * Remember you can only change the shape positions, not their number when updating a polygon.
  33831. */
  33832. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33833. var options = {
  33834. shape: shape,
  33835. holes: holes,
  33836. updatable: updatable,
  33837. sideOrientation: sideOrientation
  33838. };
  33839. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33840. };
  33841. /**
  33842. * Creates an extruded polygon mesh, with depth in the Y direction.
  33843. * Please consider using the same method from the MeshBuilder class instead.
  33844. */
  33845. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33846. var options = {
  33847. shape: shape,
  33848. holes: holes,
  33849. depth: depth,
  33850. updatable: updatable,
  33851. sideOrientation: sideOrientation
  33852. };
  33853. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33854. };
  33855. /**
  33856. * Creates an extruded shape mesh.
  33857. * 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.
  33858. * Please consider using the same method from the MeshBuilder class instead.
  33859. *
  33860. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33861. * 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
  33862. * extruded along the Z axis.
  33863. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33864. * 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.
  33865. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33866. * 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
  33867. * 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
  33868. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33870. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33871. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33872. */
  33873. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33874. if (scene === void 0) { scene = null; }
  33875. var options = {
  33876. shape: shape,
  33877. path: path,
  33878. scale: scale,
  33879. rotation: rotation,
  33880. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33881. sideOrientation: sideOrientation,
  33882. instance: instance,
  33883. updatable: updatable
  33884. };
  33885. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33886. };
  33887. /**
  33888. * Creates an custom extruded shape mesh.
  33889. * 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.
  33890. * Please consider using the same method from the MeshBuilder class instead.
  33891. *
  33892. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33893. * 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
  33894. * extruded along the Z axis.
  33895. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33896. * 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
  33897. * and the distance of this point from the begining of the path :
  33898. * ```javascript
  33899. * var rotationFunction = function(i, distance) {
  33900. * // do things
  33901. * return rotationValue; }
  33902. * ```
  33903. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33904. * 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
  33905. * and the distance of this point from the begining of the path :
  33906. * ```javascript
  33907. * var scaleFunction = function(i, distance) {
  33908. * // do things
  33909. * return scaleValue;}
  33910. * ```
  33911. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33912. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33913. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33914. * 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
  33915. * 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
  33916. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33918. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33920. */
  33921. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33922. var options = {
  33923. shape: shape,
  33924. path: path,
  33925. scaleFunction: scaleFunction,
  33926. rotationFunction: rotationFunction,
  33927. ribbonCloseArray: ribbonCloseArray,
  33928. ribbonClosePath: ribbonClosePath,
  33929. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33930. sideOrientation: sideOrientation,
  33931. instance: instance,
  33932. updatable: updatable
  33933. };
  33934. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33935. };
  33936. /**
  33937. * Creates lathe mesh.
  33938. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33939. * Please consider using the same method from the MeshBuilder class instead.
  33940. * 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
  33941. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33942. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33943. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33945. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33947. */
  33948. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33949. var options = {
  33950. shape: shape,
  33951. radius: radius,
  33952. tessellation: tessellation,
  33953. sideOrientation: sideOrientation,
  33954. updatable: updatable
  33955. };
  33956. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33957. };
  33958. /**
  33959. * Creates a plane mesh.
  33960. * Please consider using the same method from the MeshBuilder class instead.
  33961. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33963. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33965. */
  33966. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33967. var options = {
  33968. size: size,
  33969. width: size,
  33970. height: size,
  33971. sideOrientation: sideOrientation,
  33972. updatable: updatable
  33973. };
  33974. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33975. };
  33976. /**
  33977. * Creates a ground mesh.
  33978. * Please consider using the same method from the MeshBuilder class instead.
  33979. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33980. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33982. */
  33983. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33984. var options = {
  33985. width: width,
  33986. height: height,
  33987. subdivisions: subdivisions,
  33988. updatable: updatable
  33989. };
  33990. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33991. };
  33992. /**
  33993. * Creates a tiled ground mesh.
  33994. * Please consider using the same method from the MeshBuilder class instead.
  33995. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33996. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33997. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33998. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33999. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34000. * numbers of subdivisions on the ground width and height of each tile.
  34001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34002. */
  34003. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34004. var options = {
  34005. xmin: xmin,
  34006. zmin: zmin,
  34007. xmax: xmax,
  34008. zmax: zmax,
  34009. subdivisions: subdivisions,
  34010. precision: precision,
  34011. updatable: updatable
  34012. };
  34013. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34014. };
  34015. /**
  34016. * Creates a ground mesh from a height map.
  34017. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34018. * Please consider using the same method from the MeshBuilder class instead.
  34019. * The parameter `url` sets the URL of the height map image resource.
  34020. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34021. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34022. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34023. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34024. * 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).
  34025. * This function is passed the newly built mesh :
  34026. * ```javascript
  34027. * function(mesh) { // do things
  34028. * return; }
  34029. * ```
  34030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34031. */
  34032. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34033. var options = {
  34034. width: width,
  34035. height: height,
  34036. subdivisions: subdivisions,
  34037. minHeight: minHeight,
  34038. maxHeight: maxHeight,
  34039. updatable: updatable,
  34040. onReady: onReady
  34041. };
  34042. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34043. };
  34044. /**
  34045. * Creates a tube mesh.
  34046. * 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.
  34047. * Please consider using the same method from the MeshBuilder class instead.
  34048. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34049. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34050. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34051. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34052. * 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.
  34053. * It must return a radius value (positive float) :
  34054. * ```javascript
  34055. * var radiusFunction = function(i, distance) {
  34056. * // do things
  34057. * return radius; }
  34058. * ```
  34059. * 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
  34060. * 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
  34061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34062. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34064. */
  34065. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34066. var options = {
  34067. path: path,
  34068. radius: radius,
  34069. tessellation: tessellation,
  34070. radiusFunction: radiusFunction,
  34071. arc: 1,
  34072. cap: cap,
  34073. updatable: updatable,
  34074. sideOrientation: sideOrientation,
  34075. instance: instance
  34076. };
  34077. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34078. };
  34079. /**
  34080. * Creates a polyhedron mesh.
  34081. * Please consider using the same method from the MeshBuilder class instead.
  34082. * 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
  34083. * to choose the wanted type.
  34084. * The parameter `size` (positive float, default 1) sets the polygon size.
  34085. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34086. * 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`.
  34087. * 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
  34088. * 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)`).
  34089. * 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
  34090. * 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.
  34091. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34092. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34093. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34094. */
  34095. Mesh.CreatePolyhedron = function (name, options, scene) {
  34096. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34097. };
  34098. /**
  34099. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34100. * Please consider using the same method from the MeshBuilder class instead.
  34101. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34102. * 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`).
  34103. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34104. * 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.
  34105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34106. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34108. */
  34109. Mesh.CreateIcoSphere = function (name, options, scene) {
  34110. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34111. };
  34112. /**
  34113. * Creates a decal mesh.
  34114. * Please consider using the same method from the MeshBuilder class instead.
  34115. * 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.
  34116. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34117. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34118. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34119. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34120. */
  34121. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34122. var options = {
  34123. position: position,
  34124. normal: normal,
  34125. size: size,
  34126. angle: angle
  34127. };
  34128. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34129. };
  34130. // Skeletons
  34131. /**
  34132. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34133. */
  34134. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34135. if (!this._sourcePositions) {
  34136. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34137. if (!source) {
  34138. return this._sourcePositions;
  34139. }
  34140. this._sourcePositions = new Float32Array(source);
  34141. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34142. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34143. }
  34144. }
  34145. return this._sourcePositions;
  34146. };
  34147. /**
  34148. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34149. */
  34150. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34151. if (!this._sourceNormals) {
  34152. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34153. if (!source) {
  34154. return this._sourceNormals;
  34155. }
  34156. this._sourceNormals = new Float32Array(source);
  34157. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34158. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34159. }
  34160. }
  34161. return this._sourceNormals;
  34162. };
  34163. /**
  34164. * Updates the vertex buffer by applying transformation from the bones.
  34165. * Returns the Mesh.
  34166. *
  34167. * @param {skeleton} skeleton to apply
  34168. */
  34169. Mesh.prototype.applySkeleton = function (skeleton) {
  34170. if (!this.geometry) {
  34171. return this;
  34172. }
  34173. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34174. return this;
  34175. }
  34176. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34177. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34178. return this;
  34179. }
  34180. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34181. return this;
  34182. }
  34183. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34184. return this;
  34185. }
  34186. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34187. return this;
  34188. }
  34189. if (!this._sourcePositions) {
  34190. var submeshes = this.subMeshes.slice();
  34191. this.setPositionsForCPUSkinning();
  34192. this.subMeshes = submeshes;
  34193. }
  34194. if (!this._sourceNormals) {
  34195. this.setNormalsForCPUSkinning();
  34196. }
  34197. // positionsData checks for not being Float32Array will only pass at most once
  34198. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34199. if (!positionsData) {
  34200. return this;
  34201. }
  34202. if (!(positionsData instanceof Float32Array)) {
  34203. positionsData = new Float32Array(positionsData);
  34204. }
  34205. // normalsData checks for not being Float32Array will only pass at most once
  34206. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34207. if (!normalsData) {
  34208. return this;
  34209. }
  34210. if (!(normalsData instanceof Float32Array)) {
  34211. normalsData = new Float32Array(normalsData);
  34212. }
  34213. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34214. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34215. if (!matricesWeightsData || !matricesIndicesData) {
  34216. return this;
  34217. }
  34218. var needExtras = this.numBoneInfluencers > 4;
  34219. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34220. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34221. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34222. var tempVector3 = BABYLON.Vector3.Zero();
  34223. var finalMatrix = new BABYLON.Matrix();
  34224. var tempMatrix = new BABYLON.Matrix();
  34225. var matWeightIdx = 0;
  34226. var inf;
  34227. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34228. var weight;
  34229. for (inf = 0; inf < 4; inf++) {
  34230. weight = matricesWeightsData[matWeightIdx + inf];
  34231. if (weight > 0) {
  34232. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34233. finalMatrix.addToSelf(tempMatrix);
  34234. }
  34235. else
  34236. break;
  34237. }
  34238. if (needExtras) {
  34239. for (inf = 0; inf < 4; inf++) {
  34240. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34241. if (weight > 0) {
  34242. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34243. finalMatrix.addToSelf(tempMatrix);
  34244. }
  34245. else
  34246. break;
  34247. }
  34248. }
  34249. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34250. tempVector3.toArray(positionsData, index);
  34251. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34252. tempVector3.toArray(normalsData, index);
  34253. finalMatrix.reset();
  34254. }
  34255. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34256. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34257. return this;
  34258. };
  34259. // Tools
  34260. /**
  34261. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34262. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34263. */
  34264. Mesh.MinMax = function (meshes) {
  34265. var minVector = null;
  34266. var maxVector = null;
  34267. meshes.forEach(function (mesh, index, array) {
  34268. var boundingInfo = mesh.getBoundingInfo();
  34269. var boundingBox = boundingInfo.boundingBox;
  34270. if (!minVector || !maxVector) {
  34271. minVector = boundingBox.minimumWorld;
  34272. maxVector = boundingBox.maximumWorld;
  34273. }
  34274. else {
  34275. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34276. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34277. }
  34278. });
  34279. if (!minVector || !maxVector) {
  34280. return {
  34281. min: BABYLON.Vector3.Zero(),
  34282. max: BABYLON.Vector3.Zero()
  34283. };
  34284. }
  34285. return {
  34286. min: minVector,
  34287. max: maxVector
  34288. };
  34289. };
  34290. /**
  34291. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34292. */
  34293. Mesh.Center = function (meshesOrMinMaxVector) {
  34294. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34295. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34296. };
  34297. /**
  34298. * Merge the array of meshes into a single mesh for performance reasons.
  34299. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34300. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34301. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34302. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34303. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34304. */
  34305. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34306. if (disposeSource === void 0) { disposeSource = true; }
  34307. var index;
  34308. if (!allow32BitsIndices) {
  34309. var totalVertices = 0;
  34310. // Counting vertices
  34311. for (index = 0; index < meshes.length; index++) {
  34312. if (meshes[index]) {
  34313. totalVertices += meshes[index].getTotalVertices();
  34314. if (totalVertices > 65536) {
  34315. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34316. return null;
  34317. }
  34318. }
  34319. }
  34320. }
  34321. // Merge
  34322. var vertexData = null;
  34323. var otherVertexData;
  34324. var indiceArray = new Array();
  34325. var source = null;
  34326. for (index = 0; index < meshes.length; index++) {
  34327. if (meshes[index]) {
  34328. meshes[index].computeWorldMatrix(true);
  34329. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34330. otherVertexData.transform(meshes[index].getWorldMatrix());
  34331. if (vertexData) {
  34332. vertexData.merge(otherVertexData);
  34333. }
  34334. else {
  34335. vertexData = otherVertexData;
  34336. source = meshes[index];
  34337. }
  34338. if (subdivideWithSubMeshes) {
  34339. indiceArray.push(meshes[index].getTotalIndices());
  34340. }
  34341. }
  34342. }
  34343. source = source;
  34344. if (!meshSubclass) {
  34345. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34346. }
  34347. vertexData.applyToMesh(meshSubclass);
  34348. // Setting properties
  34349. meshSubclass.material = source.material;
  34350. meshSubclass.checkCollisions = source.checkCollisions;
  34351. // Cleaning
  34352. if (disposeSource) {
  34353. for (index = 0; index < meshes.length; index++) {
  34354. if (meshes[index]) {
  34355. meshes[index].dispose();
  34356. }
  34357. }
  34358. }
  34359. // Subdivide
  34360. if (subdivideWithSubMeshes) {
  34361. //-- removal of global submesh
  34362. meshSubclass.releaseSubMeshes();
  34363. index = 0;
  34364. var offset = 0;
  34365. //-- apply subdivision according to index table
  34366. while (index < indiceArray.length) {
  34367. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34368. offset += indiceArray[index];
  34369. index++;
  34370. }
  34371. }
  34372. return meshSubclass;
  34373. };
  34374. // Consts
  34375. Mesh._FRONTSIDE = 0;
  34376. Mesh._BACKSIDE = 1;
  34377. Mesh._DOUBLESIDE = 2;
  34378. Mesh._DEFAULTSIDE = 0;
  34379. Mesh._NO_CAP = 0;
  34380. Mesh._CAP_START = 1;
  34381. Mesh._CAP_END = 2;
  34382. Mesh._CAP_ALL = 3;
  34383. return Mesh;
  34384. }(BABYLON.AbstractMesh));
  34385. BABYLON.Mesh = Mesh;
  34386. })(BABYLON || (BABYLON = {}));
  34387. //# sourceMappingURL=babylon.mesh.js.map
  34388. var BABYLON;
  34389. (function (BABYLON) {
  34390. var BaseSubMesh = /** @class */ (function () {
  34391. function BaseSubMesh() {
  34392. }
  34393. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34394. get: function () {
  34395. return this._materialEffect;
  34396. },
  34397. enumerable: true,
  34398. configurable: true
  34399. });
  34400. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34401. if (defines === void 0) { defines = null; }
  34402. if (this._materialEffect === effect) {
  34403. if (!effect) {
  34404. this._materialDefines = null;
  34405. }
  34406. return;
  34407. }
  34408. this._materialDefines = defines;
  34409. this._materialEffect = effect;
  34410. };
  34411. return BaseSubMesh;
  34412. }());
  34413. BABYLON.BaseSubMesh = BaseSubMesh;
  34414. var SubMesh = /** @class */ (function (_super) {
  34415. __extends(SubMesh, _super);
  34416. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34417. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34418. var _this = _super.call(this) || this;
  34419. _this.materialIndex = materialIndex;
  34420. _this.verticesStart = verticesStart;
  34421. _this.verticesCount = verticesCount;
  34422. _this.indexStart = indexStart;
  34423. _this.indexCount = indexCount;
  34424. _this._renderId = 0;
  34425. _this._mesh = mesh;
  34426. _this._renderingMesh = renderingMesh || mesh;
  34427. mesh.subMeshes.push(_this);
  34428. _this._trianglePlanes = [];
  34429. _this._id = mesh.subMeshes.length - 1;
  34430. if (createBoundingBox) {
  34431. _this.refreshBoundingInfo();
  34432. mesh.computeWorldMatrix(true);
  34433. }
  34434. return _this;
  34435. }
  34436. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34437. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34438. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34439. };
  34440. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34441. get: function () {
  34442. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34443. },
  34444. enumerable: true,
  34445. configurable: true
  34446. });
  34447. /**
  34448. * Returns the submesh BoudingInfo object.
  34449. */
  34450. SubMesh.prototype.getBoundingInfo = function () {
  34451. if (this.IsGlobal) {
  34452. return this._mesh.getBoundingInfo();
  34453. }
  34454. return this._boundingInfo;
  34455. };
  34456. /**
  34457. * Sets the submesh BoundingInfo.
  34458. * Return the SubMesh.
  34459. */
  34460. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34461. this._boundingInfo = boundingInfo;
  34462. return this;
  34463. };
  34464. /**
  34465. * Returns the mesh of the current submesh.
  34466. */
  34467. SubMesh.prototype.getMesh = function () {
  34468. return this._mesh;
  34469. };
  34470. /**
  34471. * Returns the rendering mesh of the submesh.
  34472. */
  34473. SubMesh.prototype.getRenderingMesh = function () {
  34474. return this._renderingMesh;
  34475. };
  34476. /**
  34477. * Returns the submesh material.
  34478. */
  34479. SubMesh.prototype.getMaterial = function () {
  34480. var rootMaterial = this._renderingMesh.material;
  34481. if (rootMaterial === null || rootMaterial === undefined) {
  34482. return this._mesh.getScene().defaultMaterial;
  34483. }
  34484. else if (rootMaterial.getSubMaterial) {
  34485. var multiMaterial = rootMaterial;
  34486. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34487. if (this._currentMaterial !== effectiveMaterial) {
  34488. this._currentMaterial = effectiveMaterial;
  34489. this._materialDefines = null;
  34490. }
  34491. return effectiveMaterial;
  34492. }
  34493. return rootMaterial;
  34494. };
  34495. // Methods
  34496. /**
  34497. * Sets a new updated BoundingInfo object to the submesh.
  34498. * Returns the SubMesh.
  34499. */
  34500. SubMesh.prototype.refreshBoundingInfo = function () {
  34501. this._lastColliderWorldVertices = null;
  34502. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34503. return this;
  34504. }
  34505. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34506. if (!data) {
  34507. this._boundingInfo = this._mesh.getBoundingInfo();
  34508. return this;
  34509. }
  34510. var indices = this._renderingMesh.getIndices();
  34511. var extend;
  34512. //is this the only submesh?
  34513. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34514. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34515. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34516. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34517. }
  34518. else {
  34519. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34520. }
  34521. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34522. return this;
  34523. };
  34524. SubMesh.prototype._checkCollision = function (collider) {
  34525. var boundingInfo = this.getBoundingInfo();
  34526. return boundingInfo._checkCollision(collider);
  34527. };
  34528. /**
  34529. * Updates the submesh BoundingInfo.
  34530. * Returns the Submesh.
  34531. */
  34532. SubMesh.prototype.updateBoundingInfo = function (world) {
  34533. var boundingInfo = this.getBoundingInfo();
  34534. if (!boundingInfo) {
  34535. this.refreshBoundingInfo();
  34536. boundingInfo = this.getBoundingInfo();
  34537. }
  34538. boundingInfo.update(world);
  34539. return this;
  34540. };
  34541. /**
  34542. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34543. * Boolean returned.
  34544. */
  34545. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34546. var boundingInfo = this.getBoundingInfo();
  34547. if (!boundingInfo) {
  34548. return false;
  34549. }
  34550. return boundingInfo.isInFrustum(frustumPlanes);
  34551. };
  34552. /**
  34553. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34554. * Boolean returned.
  34555. */
  34556. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34557. var boundingInfo = this.getBoundingInfo();
  34558. if (!boundingInfo) {
  34559. return false;
  34560. }
  34561. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34562. };
  34563. /**
  34564. * Renders the submesh.
  34565. * Returns it.
  34566. */
  34567. SubMesh.prototype.render = function (enableAlphaMode) {
  34568. this._renderingMesh.render(this, enableAlphaMode);
  34569. return this;
  34570. };
  34571. /**
  34572. * Returns a new Index Buffer.
  34573. * Type returned : WebGLBuffer.
  34574. */
  34575. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34576. if (!this._linesIndexBuffer) {
  34577. var linesIndices = [];
  34578. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34579. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34580. }
  34581. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34582. this.linesIndexCount = linesIndices.length;
  34583. }
  34584. return this._linesIndexBuffer;
  34585. };
  34586. /**
  34587. * True is the passed Ray intersects the submesh bounding box.
  34588. * Boolean returned.
  34589. */
  34590. SubMesh.prototype.canIntersects = function (ray) {
  34591. var boundingInfo = this.getBoundingInfo();
  34592. if (!boundingInfo) {
  34593. return false;
  34594. }
  34595. return ray.intersectsBox(boundingInfo.boundingBox);
  34596. };
  34597. /**
  34598. * Returns an object IntersectionInfo.
  34599. */
  34600. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34601. var intersectInfo = null;
  34602. var material = this.getMaterial();
  34603. if (!material) {
  34604. return null;
  34605. }
  34606. switch (material.fillMode) {
  34607. case BABYLON.Material.PointListDrawMode:
  34608. case BABYLON.Material.LineListDrawMode:
  34609. case BABYLON.Material.LineLoopDrawMode:
  34610. case BABYLON.Material.LineStripDrawMode:
  34611. case BABYLON.Material.TriangleFanDrawMode:
  34612. case BABYLON.Material.TriangleStripDrawMode:
  34613. return null;
  34614. }
  34615. // LineMesh first as it's also a Mesh...
  34616. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34617. var lineMesh = this._mesh;
  34618. // Line test
  34619. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34620. var p0 = positions[indices[index]];
  34621. var p1 = positions[indices[index + 1]];
  34622. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34623. if (length < 0) {
  34624. continue;
  34625. }
  34626. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34627. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34628. if (fastCheck) {
  34629. break;
  34630. }
  34631. }
  34632. }
  34633. }
  34634. else {
  34635. // Triangles test
  34636. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34637. var p0 = positions[indices[index]];
  34638. var p1 = positions[indices[index + 1]];
  34639. var p2 = positions[indices[index + 2]];
  34640. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34641. if (currentIntersectInfo) {
  34642. if (currentIntersectInfo.distance < 0) {
  34643. continue;
  34644. }
  34645. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34646. intersectInfo = currentIntersectInfo;
  34647. intersectInfo.faceId = index / 3;
  34648. if (fastCheck) {
  34649. break;
  34650. }
  34651. }
  34652. }
  34653. }
  34654. }
  34655. return intersectInfo;
  34656. };
  34657. SubMesh.prototype._rebuild = function () {
  34658. if (this._linesIndexBuffer) {
  34659. this._linesIndexBuffer = null;
  34660. }
  34661. };
  34662. // Clone
  34663. /**
  34664. * Creates a new Submesh from the passed Mesh.
  34665. */
  34666. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34667. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34668. if (!this.IsGlobal) {
  34669. var boundingInfo = this.getBoundingInfo();
  34670. if (!boundingInfo) {
  34671. return result;
  34672. }
  34673. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34674. }
  34675. return result;
  34676. };
  34677. // Dispose
  34678. /**
  34679. * Disposes the Submesh.
  34680. * Returns nothing.
  34681. */
  34682. SubMesh.prototype.dispose = function () {
  34683. if (this._linesIndexBuffer) {
  34684. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34685. this._linesIndexBuffer = null;
  34686. }
  34687. // Remove from mesh
  34688. var index = this._mesh.subMeshes.indexOf(this);
  34689. this._mesh.subMeshes.splice(index, 1);
  34690. };
  34691. // Statics
  34692. /**
  34693. * Creates a new Submesh from the passed parameters :
  34694. * - materialIndex (integer) : the index of the main mesh material.
  34695. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34696. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34697. * - mesh (Mesh) : the main mesh to create the submesh from.
  34698. * - renderingMesh (optional Mesh) : rendering mesh.
  34699. */
  34700. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34701. var minVertexIndex = Number.MAX_VALUE;
  34702. var maxVertexIndex = -Number.MAX_VALUE;
  34703. renderingMesh = (renderingMesh || mesh);
  34704. var indices = renderingMesh.getIndices();
  34705. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34706. var vertexIndex = indices[index];
  34707. if (vertexIndex < minVertexIndex)
  34708. minVertexIndex = vertexIndex;
  34709. if (vertexIndex > maxVertexIndex)
  34710. maxVertexIndex = vertexIndex;
  34711. }
  34712. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34713. };
  34714. return SubMesh;
  34715. }(BaseSubMesh));
  34716. BABYLON.SubMesh = SubMesh;
  34717. })(BABYLON || (BABYLON = {}));
  34718. //# sourceMappingURL=babylon.subMesh.js.map
  34719. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34720. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34721. s = arguments[i];
  34722. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34723. t[p] = s[p];
  34724. }
  34725. return t;
  34726. };
  34727. var BABYLON;
  34728. (function (BABYLON) {
  34729. /**
  34730. * Manages the defines for the Material
  34731. */
  34732. var MaterialDefines = /** @class */ (function () {
  34733. function MaterialDefines() {
  34734. this._isDirty = true;
  34735. /** @hidden */
  34736. this._areLightsDirty = true;
  34737. /** @hidden */
  34738. this._areAttributesDirty = true;
  34739. /** @hidden */
  34740. this._areTexturesDirty = true;
  34741. /** @hidden */
  34742. this._areFresnelDirty = true;
  34743. /** @hidden */
  34744. this._areMiscDirty = true;
  34745. /** @hidden */
  34746. this._areImageProcessingDirty = true;
  34747. /** @hidden */
  34748. this._normals = false;
  34749. /** @hidden */
  34750. this._uvs = false;
  34751. /** @hidden */
  34752. this._needNormals = false;
  34753. /** @hidden */
  34754. this._needUVs = false;
  34755. }
  34756. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34757. /**
  34758. * Specifies if the material needs to be re-calculated
  34759. */
  34760. get: function () {
  34761. return this._isDirty;
  34762. },
  34763. enumerable: true,
  34764. configurable: true
  34765. });
  34766. /**
  34767. * Marks the material to indicate that it has been re-calculated
  34768. */
  34769. MaterialDefines.prototype.markAsProcessed = function () {
  34770. this._isDirty = false;
  34771. this._areAttributesDirty = false;
  34772. this._areTexturesDirty = false;
  34773. this._areFresnelDirty = false;
  34774. this._areLightsDirty = false;
  34775. this._areMiscDirty = false;
  34776. this._areImageProcessingDirty = false;
  34777. };
  34778. /**
  34779. * Marks the material to indicate that it needs to be re-calculated
  34780. */
  34781. MaterialDefines.prototype.markAsUnprocessed = function () {
  34782. this._isDirty = true;
  34783. };
  34784. /**
  34785. * Marks the material to indicate all of its defines need to be re-calculated
  34786. */
  34787. MaterialDefines.prototype.markAllAsDirty = function () {
  34788. this._areTexturesDirty = true;
  34789. this._areAttributesDirty = true;
  34790. this._areLightsDirty = true;
  34791. this._areFresnelDirty = true;
  34792. this._areMiscDirty = true;
  34793. this._areImageProcessingDirty = true;
  34794. this._isDirty = true;
  34795. };
  34796. /**
  34797. * Marks the material to indicate that image processing needs to be re-calculated
  34798. */
  34799. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34800. this._areImageProcessingDirty = true;
  34801. this._isDirty = true;
  34802. };
  34803. /**
  34804. * Marks the material to indicate the lights need to be re-calculated
  34805. */
  34806. MaterialDefines.prototype.markAsLightDirty = function () {
  34807. this._areLightsDirty = true;
  34808. this._isDirty = true;
  34809. };
  34810. /**
  34811. * Marks the attribute state as changed
  34812. */
  34813. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34814. this._areAttributesDirty = true;
  34815. this._isDirty = true;
  34816. };
  34817. /**
  34818. * Marks the texture state as changed
  34819. */
  34820. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34821. this._areTexturesDirty = true;
  34822. this._isDirty = true;
  34823. };
  34824. /**
  34825. * Marks the fresnel state as changed
  34826. */
  34827. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34828. this._areFresnelDirty = true;
  34829. this._isDirty = true;
  34830. };
  34831. /**
  34832. * Marks the misc state as changed
  34833. */
  34834. MaterialDefines.prototype.markAsMiscDirty = function () {
  34835. this._areMiscDirty = true;
  34836. this._isDirty = true;
  34837. };
  34838. /**
  34839. * Rebuilds the material defines
  34840. */
  34841. MaterialDefines.prototype.rebuild = function () {
  34842. if (this._keys) {
  34843. delete this._keys;
  34844. }
  34845. this._keys = [];
  34846. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34847. var key = _a[_i];
  34848. if (key[0] === "_") {
  34849. continue;
  34850. }
  34851. this._keys.push(key);
  34852. }
  34853. };
  34854. /**
  34855. * Specifies if two material defines are equal
  34856. * @param other - A material define instance to compare to
  34857. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34858. */
  34859. MaterialDefines.prototype.isEqual = function (other) {
  34860. if (this._keys.length !== other._keys.length) {
  34861. return false;
  34862. }
  34863. for (var index = 0; index < this._keys.length; index++) {
  34864. var prop = this._keys[index];
  34865. if (this[prop] !== other[prop]) {
  34866. return false;
  34867. }
  34868. }
  34869. return true;
  34870. };
  34871. /**
  34872. * Clones this instance's defines to another instance
  34873. * @param other - material defines to clone values to
  34874. */
  34875. MaterialDefines.prototype.cloneTo = function (other) {
  34876. if (this._keys.length !== other._keys.length) {
  34877. other._keys = this._keys.slice(0);
  34878. }
  34879. for (var index = 0; index < this._keys.length; index++) {
  34880. var prop = this._keys[index];
  34881. other[prop] = this[prop];
  34882. }
  34883. };
  34884. /**
  34885. * Resets the material define values
  34886. */
  34887. MaterialDefines.prototype.reset = function () {
  34888. for (var index = 0; index < this._keys.length; index++) {
  34889. var prop = this._keys[index];
  34890. var type = typeof this[prop];
  34891. switch (type) {
  34892. case "number":
  34893. this[prop] = 0;
  34894. break;
  34895. case "string":
  34896. this[prop] = "";
  34897. break;
  34898. default:
  34899. this[prop] = false;
  34900. break;
  34901. }
  34902. }
  34903. };
  34904. /**
  34905. * Converts the material define values to a string
  34906. * @returns - String of material define information
  34907. */
  34908. MaterialDefines.prototype.toString = function () {
  34909. var result = "";
  34910. for (var index = 0; index < this._keys.length; index++) {
  34911. var prop = this._keys[index];
  34912. var value = this[prop];
  34913. var type = typeof value;
  34914. switch (type) {
  34915. case "number":
  34916. case "string":
  34917. result += "#define " + prop + " " + value + "\n";
  34918. break;
  34919. default:
  34920. if (value) {
  34921. result += "#define " + prop + "\n";
  34922. }
  34923. break;
  34924. }
  34925. }
  34926. return result;
  34927. };
  34928. return MaterialDefines;
  34929. }());
  34930. BABYLON.MaterialDefines = MaterialDefines;
  34931. /**
  34932. * Base class for the main features of a material in Babylon.js
  34933. */
  34934. var Material = /** @class */ (function () {
  34935. /**
  34936. * Creates a material instance
  34937. * @param name defines the name of the material
  34938. * @param scene defines the scene to reference
  34939. * @param doNotAdd specifies if the material should be added to the scene
  34940. */
  34941. function Material(name, scene, doNotAdd) {
  34942. /**
  34943. * Specifies if the ready state should be checked on each call
  34944. */
  34945. this.checkReadyOnEveryCall = false;
  34946. /**
  34947. * Specifies if the ready state should be checked once
  34948. */
  34949. this.checkReadyOnlyOnce = false;
  34950. /**
  34951. * The state of the material
  34952. */
  34953. this.state = "";
  34954. /**
  34955. * The alpha value of the material
  34956. */
  34957. this._alpha = 1.0;
  34958. /**
  34959. * Specifies if back face culling is enabled
  34960. */
  34961. this._backFaceCulling = true;
  34962. /**
  34963. * Specifies if the material should be serialized
  34964. */
  34965. this.doNotSerialize = false;
  34966. /**
  34967. * Specifies if the effect should be stored on sub meshes
  34968. */
  34969. this.storeEffectOnSubMeshes = false;
  34970. /**
  34971. * An event triggered when the material is disposed
  34972. */
  34973. this.onDisposeObservable = new BABYLON.Observable();
  34974. /**
  34975. * An event triggered when the material is bound
  34976. */
  34977. this.onBindObservable = new BABYLON.Observable();
  34978. /**
  34979. * An event triggered when the material is unbound
  34980. */
  34981. this.onUnBindObservable = new BABYLON.Observable();
  34982. /**
  34983. * Stores the value of the alpha mode
  34984. */
  34985. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34986. /**
  34987. * Stores the state of the need depth pre-pass value
  34988. */
  34989. this._needDepthPrePass = false;
  34990. /**
  34991. * Specifies if depth writing should be disabled
  34992. */
  34993. this.disableDepthWrite = false;
  34994. /**
  34995. * Specifies if depth writing should be forced
  34996. */
  34997. this.forceDepthWrite = false;
  34998. /**
  34999. * Specifies if there should be a separate pass for culling
  35000. */
  35001. this.separateCullingPass = false;
  35002. /**
  35003. * Stores the state specifing if fog should be enabled
  35004. */
  35005. this._fogEnabled = true;
  35006. /**
  35007. * Stores the size of points
  35008. */
  35009. this.pointSize = 1.0;
  35010. /**
  35011. * Stores the z offset value
  35012. */
  35013. this.zOffset = 0;
  35014. /**
  35015. * Specifies if the material was previously ready
  35016. */
  35017. this._wasPreviouslyReady = false;
  35018. /**
  35019. * Stores the fill mode state
  35020. */
  35021. this._fillMode = Material.TriangleFillMode;
  35022. this.name = name;
  35023. this.id = name || BABYLON.Tools.RandomId();
  35024. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35025. this.uniqueId = this._scene.getUniqueId();
  35026. if (this._scene.useRightHandedSystem) {
  35027. this.sideOrientation = Material.ClockWiseSideOrientation;
  35028. }
  35029. else {
  35030. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35031. }
  35032. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35033. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35034. if (!doNotAdd) {
  35035. this._scene.materials.push(this);
  35036. }
  35037. }
  35038. Object.defineProperty(Material, "TriangleFillMode", {
  35039. /**
  35040. * Returns the triangle fill mode
  35041. */
  35042. get: function () {
  35043. return Material._TriangleFillMode;
  35044. },
  35045. enumerable: true,
  35046. configurable: true
  35047. });
  35048. Object.defineProperty(Material, "WireFrameFillMode", {
  35049. /**
  35050. * Returns the wireframe mode
  35051. */
  35052. get: function () {
  35053. return Material._WireFrameFillMode;
  35054. },
  35055. enumerable: true,
  35056. configurable: true
  35057. });
  35058. Object.defineProperty(Material, "PointFillMode", {
  35059. /**
  35060. * Returns the point fill mode
  35061. */
  35062. get: function () {
  35063. return Material._PointFillMode;
  35064. },
  35065. enumerable: true,
  35066. configurable: true
  35067. });
  35068. Object.defineProperty(Material, "PointListDrawMode", {
  35069. /**
  35070. * Returns the point list draw mode
  35071. */
  35072. get: function () {
  35073. return Material._PointListDrawMode;
  35074. },
  35075. enumerable: true,
  35076. configurable: true
  35077. });
  35078. Object.defineProperty(Material, "LineListDrawMode", {
  35079. /**
  35080. * Returns the line list draw mode
  35081. */
  35082. get: function () {
  35083. return Material._LineListDrawMode;
  35084. },
  35085. enumerable: true,
  35086. configurable: true
  35087. });
  35088. Object.defineProperty(Material, "LineLoopDrawMode", {
  35089. /**
  35090. * Returns the line loop draw mode
  35091. */
  35092. get: function () {
  35093. return Material._LineLoopDrawMode;
  35094. },
  35095. enumerable: true,
  35096. configurable: true
  35097. });
  35098. Object.defineProperty(Material, "LineStripDrawMode", {
  35099. /**
  35100. * Returns the line strip draw mode
  35101. */
  35102. get: function () {
  35103. return Material._LineStripDrawMode;
  35104. },
  35105. enumerable: true,
  35106. configurable: true
  35107. });
  35108. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35109. /**
  35110. * Returns the triangle strip draw mode
  35111. */
  35112. get: function () {
  35113. return Material._TriangleStripDrawMode;
  35114. },
  35115. enumerable: true,
  35116. configurable: true
  35117. });
  35118. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35119. /**
  35120. * Returns the triangle fan draw mode
  35121. */
  35122. get: function () {
  35123. return Material._TriangleFanDrawMode;
  35124. },
  35125. enumerable: true,
  35126. configurable: true
  35127. });
  35128. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35129. /**
  35130. * Returns the clock-wise side orientation
  35131. */
  35132. get: function () {
  35133. return Material._ClockWiseSideOrientation;
  35134. },
  35135. enumerable: true,
  35136. configurable: true
  35137. });
  35138. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35139. /**
  35140. * Returns the counter clock-wise side orientation
  35141. */
  35142. get: function () {
  35143. return Material._CounterClockWiseSideOrientation;
  35144. },
  35145. enumerable: true,
  35146. configurable: true
  35147. });
  35148. Object.defineProperty(Material, "TextureDirtyFlag", {
  35149. /**
  35150. * Returns the dirty texture flag value
  35151. */
  35152. get: function () {
  35153. return Material._TextureDirtyFlag;
  35154. },
  35155. enumerable: true,
  35156. configurable: true
  35157. });
  35158. Object.defineProperty(Material, "LightDirtyFlag", {
  35159. /**
  35160. * Returns the dirty light flag value
  35161. */
  35162. get: function () {
  35163. return Material._LightDirtyFlag;
  35164. },
  35165. enumerable: true,
  35166. configurable: true
  35167. });
  35168. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35169. /**
  35170. * Returns the dirty fresnel flag value
  35171. */
  35172. get: function () {
  35173. return Material._FresnelDirtyFlag;
  35174. },
  35175. enumerable: true,
  35176. configurable: true
  35177. });
  35178. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35179. /**
  35180. * Returns the dirty attributes flag value
  35181. */
  35182. get: function () {
  35183. return Material._AttributesDirtyFlag;
  35184. },
  35185. enumerable: true,
  35186. configurable: true
  35187. });
  35188. Object.defineProperty(Material, "MiscDirtyFlag", {
  35189. /**
  35190. * Returns the dirty misc flag value
  35191. */
  35192. get: function () {
  35193. return Material._MiscDirtyFlag;
  35194. },
  35195. enumerable: true,
  35196. configurable: true
  35197. });
  35198. Object.defineProperty(Material.prototype, "alpha", {
  35199. /**
  35200. * Gets the alpha value of the material
  35201. */
  35202. get: function () {
  35203. return this._alpha;
  35204. },
  35205. /**
  35206. * Sets the alpha value of the material
  35207. */
  35208. set: function (value) {
  35209. if (this._alpha === value) {
  35210. return;
  35211. }
  35212. this._alpha = value;
  35213. this.markAsDirty(Material.MiscDirtyFlag);
  35214. },
  35215. enumerable: true,
  35216. configurable: true
  35217. });
  35218. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35219. /**
  35220. * Gets the back-face culling state
  35221. */
  35222. get: function () {
  35223. return this._backFaceCulling;
  35224. },
  35225. /**
  35226. * Sets the back-face culling state
  35227. */
  35228. set: function (value) {
  35229. if (this._backFaceCulling === value) {
  35230. return;
  35231. }
  35232. this._backFaceCulling = value;
  35233. this.markAsDirty(Material.TextureDirtyFlag);
  35234. },
  35235. enumerable: true,
  35236. configurable: true
  35237. });
  35238. Object.defineProperty(Material.prototype, "onDispose", {
  35239. /**
  35240. * Called during a dispose event
  35241. */
  35242. set: function (callback) {
  35243. if (this._onDisposeObserver) {
  35244. this.onDisposeObservable.remove(this._onDisposeObserver);
  35245. }
  35246. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35247. },
  35248. enumerable: true,
  35249. configurable: true
  35250. });
  35251. Object.defineProperty(Material.prototype, "onBind", {
  35252. /**
  35253. * Called during a bind event
  35254. */
  35255. set: function (callback) {
  35256. if (this._onBindObserver) {
  35257. this.onBindObservable.remove(this._onBindObserver);
  35258. }
  35259. this._onBindObserver = this.onBindObservable.add(callback);
  35260. },
  35261. enumerable: true,
  35262. configurable: true
  35263. });
  35264. Object.defineProperty(Material.prototype, "alphaMode", {
  35265. /**
  35266. * Gets the value of the alpha mode
  35267. */
  35268. get: function () {
  35269. return this._alphaMode;
  35270. },
  35271. /**
  35272. * Sets the value of the alpha mode.
  35273. *
  35274. * | Value | Type | Description |
  35275. * | --- | --- | --- |
  35276. * | 0 | ALPHA_DISABLE | |
  35277. * | 1 | ALPHA_ADD | |
  35278. * | 2 | ALPHA_COMBINE | |
  35279. * | 3 | ALPHA_SUBTRACT | |
  35280. * | 4 | ALPHA_MULTIPLY | |
  35281. * | 5 | ALPHA_MAXIMIZED | |
  35282. * | 6 | ALPHA_ONEONE | |
  35283. * | 7 | ALPHA_PREMULTIPLIED | |
  35284. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35285. * | 9 | ALPHA_INTERPOLATE | |
  35286. * | 10 | ALPHA_SCREENMODE | |
  35287. *
  35288. */
  35289. set: function (value) {
  35290. if (this._alphaMode === value) {
  35291. return;
  35292. }
  35293. this._alphaMode = value;
  35294. this.markAsDirty(Material.TextureDirtyFlag);
  35295. },
  35296. enumerable: true,
  35297. configurable: true
  35298. });
  35299. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35300. /**
  35301. * Gets the depth pre-pass value
  35302. */
  35303. get: function () {
  35304. return this._needDepthPrePass;
  35305. },
  35306. /**
  35307. * Sets the need depth pre-pass value
  35308. */
  35309. set: function (value) {
  35310. if (this._needDepthPrePass === value) {
  35311. return;
  35312. }
  35313. this._needDepthPrePass = value;
  35314. if (this._needDepthPrePass) {
  35315. this.checkReadyOnEveryCall = true;
  35316. }
  35317. },
  35318. enumerable: true,
  35319. configurable: true
  35320. });
  35321. Object.defineProperty(Material.prototype, "fogEnabled", {
  35322. /**
  35323. * Gets the value of the fog enabled state
  35324. */
  35325. get: function () {
  35326. return this._fogEnabled;
  35327. },
  35328. /**
  35329. * Sets the state for enabling fog
  35330. */
  35331. set: function (value) {
  35332. if (this._fogEnabled === value) {
  35333. return;
  35334. }
  35335. this._fogEnabled = value;
  35336. this.markAsDirty(Material.MiscDirtyFlag);
  35337. },
  35338. enumerable: true,
  35339. configurable: true
  35340. });
  35341. Object.defineProperty(Material.prototype, "wireframe", {
  35342. /**
  35343. * Gets a value specifying if wireframe mode is enabled
  35344. */
  35345. get: function () {
  35346. switch (this._fillMode) {
  35347. case Material.WireFrameFillMode:
  35348. case Material.LineListDrawMode:
  35349. case Material.LineLoopDrawMode:
  35350. case Material.LineStripDrawMode:
  35351. return true;
  35352. }
  35353. return this._scene.forceWireframe;
  35354. },
  35355. /**
  35356. * Sets the state of wireframe mode
  35357. */
  35358. set: function (value) {
  35359. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35360. },
  35361. enumerable: true,
  35362. configurable: true
  35363. });
  35364. Object.defineProperty(Material.prototype, "pointsCloud", {
  35365. /**
  35366. * Gets the value specifying if point clouds are enabled
  35367. */
  35368. get: function () {
  35369. switch (this._fillMode) {
  35370. case Material.PointFillMode:
  35371. case Material.PointListDrawMode:
  35372. return true;
  35373. }
  35374. return this._scene.forcePointsCloud;
  35375. },
  35376. /**
  35377. * Sets the state of point cloud mode
  35378. */
  35379. set: function (value) {
  35380. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35381. },
  35382. enumerable: true,
  35383. configurable: true
  35384. });
  35385. Object.defineProperty(Material.prototype, "fillMode", {
  35386. /**
  35387. * Gets the material fill mode
  35388. */
  35389. get: function () {
  35390. return this._fillMode;
  35391. },
  35392. /**
  35393. * Sets the material fill mode
  35394. */
  35395. set: function (value) {
  35396. if (this._fillMode === value) {
  35397. return;
  35398. }
  35399. this._fillMode = value;
  35400. this.markAsDirty(Material.MiscDirtyFlag);
  35401. },
  35402. enumerable: true,
  35403. configurable: true
  35404. });
  35405. /**
  35406. * Returns a string representation of the current material
  35407. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35408. * @returns a string with material information
  35409. */
  35410. Material.prototype.toString = function (fullDetails) {
  35411. var ret = "Name: " + this.name;
  35412. if (fullDetails) {
  35413. }
  35414. return ret;
  35415. };
  35416. /**
  35417. * Gets the class name of the material
  35418. * @returns a string with the class name of the material
  35419. */
  35420. Material.prototype.getClassName = function () {
  35421. return "Material";
  35422. };
  35423. Object.defineProperty(Material.prototype, "isFrozen", {
  35424. /**
  35425. * Specifies if updates for the material been locked
  35426. */
  35427. get: function () {
  35428. return this.checkReadyOnlyOnce;
  35429. },
  35430. enumerable: true,
  35431. configurable: true
  35432. });
  35433. /**
  35434. * Locks updates for the material
  35435. */
  35436. Material.prototype.freeze = function () {
  35437. this.checkReadyOnlyOnce = true;
  35438. };
  35439. /**
  35440. * Unlocks updates for the material
  35441. */
  35442. Material.prototype.unfreeze = function () {
  35443. this.checkReadyOnlyOnce = false;
  35444. };
  35445. /**
  35446. * Specifies if the material is ready to be used
  35447. * @param mesh defines the mesh to check
  35448. * @param useInstances specifies if instances should be used
  35449. * @returns a boolean indicating if the material is ready to be used
  35450. */
  35451. Material.prototype.isReady = function (mesh, useInstances) {
  35452. return true;
  35453. };
  35454. /**
  35455. * Specifies that the submesh is ready to be used
  35456. * @param mesh defines the mesh to check
  35457. * @param subMesh defines which submesh to check
  35458. * @param useInstances specifies that instances should be used
  35459. * @returns a boolean indicating that the submesh is ready or not
  35460. */
  35461. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35462. return false;
  35463. };
  35464. /**
  35465. * Returns the material effect
  35466. * @returns the effect associated with the material
  35467. */
  35468. Material.prototype.getEffect = function () {
  35469. return this._effect;
  35470. };
  35471. /**
  35472. * Returns the current scene
  35473. * @returns a Scene
  35474. */
  35475. Material.prototype.getScene = function () {
  35476. return this._scene;
  35477. };
  35478. /**
  35479. * Specifies if the material will require alpha blending
  35480. * @returns a boolean specifying if alpha blending is needed
  35481. */
  35482. Material.prototype.needAlphaBlending = function () {
  35483. return (this.alpha < 1.0);
  35484. };
  35485. /**
  35486. * Specifies if the mesh will require alpha blending
  35487. * @param mesh defines the mesh to check
  35488. * @returns a boolean specifying if alpha blending is needed for the mesh
  35489. */
  35490. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35491. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35492. };
  35493. /**
  35494. * Specifies if this material should be rendered in alpha test mode
  35495. * @returns a boolean specifying if an alpha test is needed.
  35496. */
  35497. Material.prototype.needAlphaTesting = function () {
  35498. return false;
  35499. };
  35500. /**
  35501. * Gets the texture used for the alpha test
  35502. * @returns the texture to use for alpha testing
  35503. */
  35504. Material.prototype.getAlphaTestTexture = function () {
  35505. return null;
  35506. };
  35507. /**
  35508. * Marks the material to indicate that it needs to be re-calculated
  35509. */
  35510. Material.prototype.markDirty = function () {
  35511. this._wasPreviouslyReady = false;
  35512. };
  35513. /** @hidden */
  35514. Material.prototype._preBind = function (effect, overrideOrientation) {
  35515. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35516. var engine = this._scene.getEngine();
  35517. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35518. var reverse = orientation === Material.ClockWiseSideOrientation;
  35519. engine.enableEffect(effect ? effect : this._effect);
  35520. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35521. return reverse;
  35522. };
  35523. /**
  35524. * Binds the material to the mesh
  35525. * @param world defines the world transformation matrix
  35526. * @param mesh defines the mesh to bind the material to
  35527. */
  35528. Material.prototype.bind = function (world, mesh) {
  35529. };
  35530. /**
  35531. * Binds the submesh to the material
  35532. * @param world defines the world transformation matrix
  35533. * @param mesh defines the mesh containing the submesh
  35534. * @param subMesh defines the submesh to bind the material to
  35535. */
  35536. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35537. };
  35538. /**
  35539. * Binds the world matrix to the material
  35540. * @param world defines the world transformation matrix
  35541. */
  35542. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35543. };
  35544. /**
  35545. * Binds the scene's uniform buffer to the effect.
  35546. * @param effect defines the effect to bind to the scene uniform buffer
  35547. * @param sceneUbo defines the uniform buffer storing scene data
  35548. */
  35549. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35550. sceneUbo.bindToEffect(effect, "Scene");
  35551. };
  35552. /**
  35553. * Binds the view matrix to the effect
  35554. * @param effect defines the effect to bind the view matrix to
  35555. */
  35556. Material.prototype.bindView = function (effect) {
  35557. if (!this._useUBO) {
  35558. effect.setMatrix("view", this.getScene().getViewMatrix());
  35559. }
  35560. else {
  35561. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35562. }
  35563. };
  35564. /**
  35565. * Binds the view projection matrix to the effect
  35566. * @param effect defines the effect to bind the view projection matrix to
  35567. */
  35568. Material.prototype.bindViewProjection = function (effect) {
  35569. if (!this._useUBO) {
  35570. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35571. }
  35572. else {
  35573. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35574. }
  35575. };
  35576. /**
  35577. * Specifies if material alpha testing should be turned on for the mesh
  35578. * @param mesh defines the mesh to check
  35579. */
  35580. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35581. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35582. };
  35583. /**
  35584. * Processes to execute after binding the material to a mesh
  35585. * @param mesh defines the rendered mesh
  35586. */
  35587. Material.prototype._afterBind = function (mesh) {
  35588. this._scene._cachedMaterial = this;
  35589. if (mesh) {
  35590. this._scene._cachedVisibility = mesh.visibility;
  35591. }
  35592. else {
  35593. this._scene._cachedVisibility = 1;
  35594. }
  35595. if (mesh) {
  35596. this.onBindObservable.notifyObservers(mesh);
  35597. }
  35598. if (this.disableDepthWrite) {
  35599. var engine = this._scene.getEngine();
  35600. this._cachedDepthWriteState = engine.getDepthWrite();
  35601. engine.setDepthWrite(false);
  35602. }
  35603. };
  35604. /**
  35605. * Unbinds the material from the mesh
  35606. */
  35607. Material.prototype.unbind = function () {
  35608. this.onUnBindObservable.notifyObservers(this);
  35609. if (this.disableDepthWrite) {
  35610. var engine = this._scene.getEngine();
  35611. engine.setDepthWrite(this._cachedDepthWriteState);
  35612. }
  35613. };
  35614. /**
  35615. * Gets the active textures from the material
  35616. * @returns an array of textures
  35617. */
  35618. Material.prototype.getActiveTextures = function () {
  35619. return [];
  35620. };
  35621. /**
  35622. * Specifies if the material uses a texture
  35623. * @param texture defines the texture to check against the material
  35624. * @returns a boolean specifying if the material uses the texture
  35625. */
  35626. Material.prototype.hasTexture = function (texture) {
  35627. return false;
  35628. };
  35629. /**
  35630. * Makes a duplicate of the material, and gives it a new name
  35631. * @param name defines the new name for the duplicated material
  35632. * @returns the cloned material
  35633. */
  35634. Material.prototype.clone = function (name) {
  35635. return null;
  35636. };
  35637. /**
  35638. * Gets the meshes bound to the material
  35639. * @returns an array of meshes bound to the material
  35640. */
  35641. Material.prototype.getBindedMeshes = function () {
  35642. var result = new Array();
  35643. for (var index = 0; index < this._scene.meshes.length; index++) {
  35644. var mesh = this._scene.meshes[index];
  35645. if (mesh.material === this) {
  35646. result.push(mesh);
  35647. }
  35648. }
  35649. return result;
  35650. };
  35651. /**
  35652. * Force shader compilation
  35653. * @param mesh defines the mesh associated with this material
  35654. * @param onCompiled defines a function to execute once the material is compiled
  35655. * @param options defines the options to configure the compilation
  35656. */
  35657. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35658. var _this = this;
  35659. var localOptions = __assign({ clipPlane: false }, options);
  35660. var subMesh = new BABYLON.BaseSubMesh();
  35661. var scene = this.getScene();
  35662. var checkReady = function () {
  35663. if (!_this._scene || !_this._scene.getEngine()) {
  35664. return;
  35665. }
  35666. if (subMesh._materialDefines) {
  35667. subMesh._materialDefines._renderId = -1;
  35668. }
  35669. var clipPlaneState = scene.clipPlane;
  35670. if (localOptions.clipPlane) {
  35671. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35672. }
  35673. if (_this.storeEffectOnSubMeshes) {
  35674. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35675. if (onCompiled) {
  35676. onCompiled(_this);
  35677. }
  35678. }
  35679. else {
  35680. setTimeout(checkReady, 16);
  35681. }
  35682. }
  35683. else {
  35684. if (_this.isReady(mesh)) {
  35685. if (onCompiled) {
  35686. onCompiled(_this);
  35687. }
  35688. }
  35689. else {
  35690. setTimeout(checkReady, 16);
  35691. }
  35692. }
  35693. if (localOptions.clipPlane) {
  35694. scene.clipPlane = clipPlaneState;
  35695. }
  35696. };
  35697. checkReady();
  35698. };
  35699. /**
  35700. * Force shader compilation
  35701. * @param mesh defines the mesh that will use this material
  35702. * @param options defines additional options for compiling the shaders
  35703. * @returns a promise that resolves when the compilation completes
  35704. */
  35705. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35706. var _this = this;
  35707. return new Promise(function (resolve) {
  35708. _this.forceCompilation(mesh, function () {
  35709. resolve();
  35710. }, options);
  35711. });
  35712. };
  35713. /**
  35714. * Marks a define in the material to indicate that it needs to be re-computed
  35715. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35716. */
  35717. Material.prototype.markAsDirty = function (flag) {
  35718. if (flag & Material.TextureDirtyFlag) {
  35719. this._markAllSubMeshesAsTexturesDirty();
  35720. }
  35721. if (flag & Material.LightDirtyFlag) {
  35722. this._markAllSubMeshesAsLightsDirty();
  35723. }
  35724. if (flag & Material.FresnelDirtyFlag) {
  35725. this._markAllSubMeshesAsFresnelDirty();
  35726. }
  35727. if (flag & Material.AttributesDirtyFlag) {
  35728. this._markAllSubMeshesAsAttributesDirty();
  35729. }
  35730. if (flag & Material.MiscDirtyFlag) {
  35731. this._markAllSubMeshesAsMiscDirty();
  35732. }
  35733. this.getScene().resetCachedMaterial();
  35734. };
  35735. /**
  35736. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35737. * @param func defines a function which checks material defines against the submeshes
  35738. */
  35739. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35740. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35741. var mesh = _a[_i];
  35742. if (!mesh.subMeshes) {
  35743. continue;
  35744. }
  35745. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35746. var subMesh = _c[_b];
  35747. if (subMesh.getMaterial() !== this) {
  35748. continue;
  35749. }
  35750. if (!subMesh._materialDefines) {
  35751. continue;
  35752. }
  35753. func(subMesh._materialDefines);
  35754. }
  35755. }
  35756. };
  35757. /**
  35758. * Indicates that image processing needs to be re-calculated for all submeshes
  35759. */
  35760. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35761. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35762. };
  35763. /**
  35764. * Indicates that textures need to be re-calculated for all submeshes
  35765. */
  35766. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35767. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35768. };
  35769. /**
  35770. * Indicates that fresnel needs to be re-calculated for all submeshes
  35771. */
  35772. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35773. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35774. };
  35775. /**
  35776. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35777. */
  35778. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35779. this._markAllSubMeshesAsDirty(function (defines) {
  35780. defines.markAsFresnelDirty();
  35781. defines.markAsMiscDirty();
  35782. });
  35783. };
  35784. /**
  35785. * Indicates that lights need to be re-calculated for all submeshes
  35786. */
  35787. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35788. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35789. };
  35790. /**
  35791. * Indicates that attributes need to be re-calculated for all submeshes
  35792. */
  35793. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35794. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35795. };
  35796. /**
  35797. * Indicates that misc needs to be re-calculated for all submeshes
  35798. */
  35799. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35800. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35801. };
  35802. /**
  35803. * Indicates that textures and misc need to be re-calculated for all submeshes
  35804. */
  35805. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35806. this._markAllSubMeshesAsDirty(function (defines) {
  35807. defines.markAsTexturesDirty();
  35808. defines.markAsMiscDirty();
  35809. });
  35810. };
  35811. /**
  35812. * Disposes the material
  35813. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35814. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35815. */
  35816. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35817. // Animations
  35818. this.getScene().stopAnimation(this);
  35819. this.getScene().freeProcessedMaterials();
  35820. // Remove from scene
  35821. var index = this._scene.materials.indexOf(this);
  35822. if (index >= 0) {
  35823. this._scene.materials.splice(index, 1);
  35824. }
  35825. // Remove from meshes
  35826. for (index = 0; index < this._scene.meshes.length; index++) {
  35827. var mesh = this._scene.meshes[index];
  35828. if (mesh.material === this) {
  35829. mesh.material = null;
  35830. if (mesh.geometry) {
  35831. var geometry = (mesh.geometry);
  35832. if (this.storeEffectOnSubMeshes) {
  35833. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35834. var subMesh = _a[_i];
  35835. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35836. if (forceDisposeEffect && subMesh._materialEffect) {
  35837. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35838. }
  35839. }
  35840. }
  35841. else {
  35842. geometry._releaseVertexArrayObject(this._effect);
  35843. }
  35844. }
  35845. }
  35846. }
  35847. this._uniformBuffer.dispose();
  35848. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35849. if (forceDisposeEffect && this._effect) {
  35850. if (!this.storeEffectOnSubMeshes) {
  35851. this._scene.getEngine()._releaseEffect(this._effect);
  35852. }
  35853. this._effect = null;
  35854. }
  35855. // Callback
  35856. this.onDisposeObservable.notifyObservers(this);
  35857. this.onDisposeObservable.clear();
  35858. this.onBindObservable.clear();
  35859. this.onUnBindObservable.clear();
  35860. };
  35861. /**
  35862. * Serializes this material
  35863. * @returns the serialized material object
  35864. */
  35865. Material.prototype.serialize = function () {
  35866. return BABYLON.SerializationHelper.Serialize(this);
  35867. };
  35868. /**
  35869. * Creates a MultiMaterial from parsed MultiMaterial data.
  35870. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35871. * @param scene defines the hosting scene
  35872. * @returns a new MultiMaterial
  35873. */
  35874. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35875. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35876. multiMaterial.id = parsedMultiMaterial.id;
  35877. if (BABYLON.Tags) {
  35878. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35879. }
  35880. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35881. var subMatId = parsedMultiMaterial.materials[matIndex];
  35882. if (subMatId) {
  35883. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35884. }
  35885. else {
  35886. multiMaterial.subMaterials.push(null);
  35887. }
  35888. }
  35889. return multiMaterial;
  35890. };
  35891. /**
  35892. * Creates a material from parsed material data
  35893. * @param parsedMaterial defines parsed material data
  35894. * @param scene defines the hosting scene
  35895. * @param rootUrl defines the root URL to use to load textures
  35896. * @returns a new material
  35897. */
  35898. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35899. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35900. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35901. }
  35902. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35903. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35904. if (!BABYLON.LegacyPBRMaterial) {
  35905. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35906. return;
  35907. }
  35908. }
  35909. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35910. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35911. };
  35912. // Triangle views
  35913. Material._TriangleFillMode = 0;
  35914. Material._WireFrameFillMode = 1;
  35915. Material._PointFillMode = 2;
  35916. // Draw modes
  35917. Material._PointListDrawMode = 3;
  35918. Material._LineListDrawMode = 4;
  35919. Material._LineLoopDrawMode = 5;
  35920. Material._LineStripDrawMode = 6;
  35921. Material._TriangleStripDrawMode = 7;
  35922. Material._TriangleFanDrawMode = 8;
  35923. /**
  35924. * Stores the clock-wise side orientation
  35925. */
  35926. Material._ClockWiseSideOrientation = 0;
  35927. /**
  35928. * Stores the counter clock-wise side orientation
  35929. */
  35930. Material._CounterClockWiseSideOrientation = 1;
  35931. /**
  35932. * The dirty texture flag value
  35933. */
  35934. Material._TextureDirtyFlag = 1;
  35935. /**
  35936. * The dirty light flag value
  35937. */
  35938. Material._LightDirtyFlag = 2;
  35939. /**
  35940. * The dirty fresnel flag value
  35941. */
  35942. Material._FresnelDirtyFlag = 4;
  35943. /**
  35944. * The dirty attribute flag value
  35945. */
  35946. Material._AttributesDirtyFlag = 8;
  35947. /**
  35948. * The dirty misc flag value
  35949. */
  35950. Material._MiscDirtyFlag = 16;
  35951. __decorate([
  35952. BABYLON.serialize()
  35953. ], Material.prototype, "id", void 0);
  35954. __decorate([
  35955. BABYLON.serialize()
  35956. ], Material.prototype, "uniqueId", void 0);
  35957. __decorate([
  35958. BABYLON.serialize()
  35959. ], Material.prototype, "name", void 0);
  35960. __decorate([
  35961. BABYLON.serialize()
  35962. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35963. __decorate([
  35964. BABYLON.serialize()
  35965. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35966. __decorate([
  35967. BABYLON.serialize()
  35968. ], Material.prototype, "state", void 0);
  35969. __decorate([
  35970. BABYLON.serialize("alpha")
  35971. ], Material.prototype, "_alpha", void 0);
  35972. __decorate([
  35973. BABYLON.serialize("backFaceCulling")
  35974. ], Material.prototype, "_backFaceCulling", void 0);
  35975. __decorate([
  35976. BABYLON.serialize()
  35977. ], Material.prototype, "sideOrientation", void 0);
  35978. __decorate([
  35979. BABYLON.serialize("alphaMode")
  35980. ], Material.prototype, "_alphaMode", void 0);
  35981. __decorate([
  35982. BABYLON.serialize()
  35983. ], Material.prototype, "_needDepthPrePass", void 0);
  35984. __decorate([
  35985. BABYLON.serialize()
  35986. ], Material.prototype, "disableDepthWrite", void 0);
  35987. __decorate([
  35988. BABYLON.serialize()
  35989. ], Material.prototype, "forceDepthWrite", void 0);
  35990. __decorate([
  35991. BABYLON.serialize()
  35992. ], Material.prototype, "separateCullingPass", void 0);
  35993. __decorate([
  35994. BABYLON.serialize("fogEnabled")
  35995. ], Material.prototype, "_fogEnabled", void 0);
  35996. __decorate([
  35997. BABYLON.serialize()
  35998. ], Material.prototype, "pointSize", void 0);
  35999. __decorate([
  36000. BABYLON.serialize()
  36001. ], Material.prototype, "zOffset", void 0);
  36002. __decorate([
  36003. BABYLON.serialize()
  36004. ], Material.prototype, "wireframe", null);
  36005. __decorate([
  36006. BABYLON.serialize()
  36007. ], Material.prototype, "pointsCloud", null);
  36008. __decorate([
  36009. BABYLON.serialize()
  36010. ], Material.prototype, "fillMode", null);
  36011. return Material;
  36012. }());
  36013. BABYLON.Material = Material;
  36014. })(BABYLON || (BABYLON = {}));
  36015. //# sourceMappingURL=babylon.material.js.map
  36016. var BABYLON;
  36017. (function (BABYLON) {
  36018. var UniformBuffer = /** @class */ (function () {
  36019. /**
  36020. * Uniform buffer objects.
  36021. *
  36022. * Handles blocks of uniform on the GPU.
  36023. *
  36024. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36025. *
  36026. * For more information, please refer to :
  36027. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36028. */
  36029. function UniformBuffer(engine, data, dynamic) {
  36030. this._engine = engine;
  36031. this._noUBO = !engine.supportsUniformBuffers;
  36032. this._dynamic = dynamic;
  36033. this._data = data || [];
  36034. this._uniformLocations = {};
  36035. this._uniformSizes = {};
  36036. this._uniformLocationPointer = 0;
  36037. this._needSync = false;
  36038. if (this._noUBO) {
  36039. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36040. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36041. this.updateFloat = this._updateFloatForEffect;
  36042. this.updateFloat2 = this._updateFloat2ForEffect;
  36043. this.updateFloat3 = this._updateFloat3ForEffect;
  36044. this.updateFloat4 = this._updateFloat4ForEffect;
  36045. this.updateMatrix = this._updateMatrixForEffect;
  36046. this.updateVector3 = this._updateVector3ForEffect;
  36047. this.updateVector4 = this._updateVector4ForEffect;
  36048. this.updateColor3 = this._updateColor3ForEffect;
  36049. this.updateColor4 = this._updateColor4ForEffect;
  36050. }
  36051. else {
  36052. this._engine._uniformBuffers.push(this);
  36053. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36054. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36055. this.updateFloat = this._updateFloatForUniform;
  36056. this.updateFloat2 = this._updateFloat2ForUniform;
  36057. this.updateFloat3 = this._updateFloat3ForUniform;
  36058. this.updateFloat4 = this._updateFloat4ForUniform;
  36059. this.updateMatrix = this._updateMatrixForUniform;
  36060. this.updateVector3 = this._updateVector3ForUniform;
  36061. this.updateVector4 = this._updateVector4ForUniform;
  36062. this.updateColor3 = this._updateColor3ForUniform;
  36063. this.updateColor4 = this._updateColor4ForUniform;
  36064. }
  36065. }
  36066. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36067. // Properties
  36068. /**
  36069. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36070. * or just falling back on setUniformXXX calls.
  36071. */
  36072. get: function () {
  36073. return !this._noUBO;
  36074. },
  36075. enumerable: true,
  36076. configurable: true
  36077. });
  36078. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36079. /**
  36080. * Indicates if the WebGL underlying uniform buffer is in sync
  36081. * with the javascript cache data.
  36082. */
  36083. get: function () {
  36084. return !this._needSync;
  36085. },
  36086. enumerable: true,
  36087. configurable: true
  36088. });
  36089. /**
  36090. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36091. * Also, a dynamic UniformBuffer will disable cache verification and always
  36092. * update the underlying WebGL uniform buffer to the GPU.
  36093. */
  36094. UniformBuffer.prototype.isDynamic = function () {
  36095. return this._dynamic !== undefined;
  36096. };
  36097. /**
  36098. * The data cache on JS side.
  36099. */
  36100. UniformBuffer.prototype.getData = function () {
  36101. return this._bufferData;
  36102. };
  36103. /**
  36104. * The underlying WebGL Uniform buffer.
  36105. */
  36106. UniformBuffer.prototype.getBuffer = function () {
  36107. return this._buffer;
  36108. };
  36109. /**
  36110. * std140 layout specifies how to align data within an UBO structure.
  36111. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36112. * for specs.
  36113. */
  36114. UniformBuffer.prototype._fillAlignment = function (size) {
  36115. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36116. // and 4x4 matrices
  36117. // TODO : change if other types are used
  36118. var alignment;
  36119. if (size <= 2) {
  36120. alignment = size;
  36121. }
  36122. else {
  36123. alignment = 4;
  36124. }
  36125. if ((this._uniformLocationPointer % alignment) !== 0) {
  36126. var oldPointer = this._uniformLocationPointer;
  36127. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36128. var diff = this._uniformLocationPointer - oldPointer;
  36129. for (var i = 0; i < diff; i++) {
  36130. this._data.push(0);
  36131. }
  36132. }
  36133. };
  36134. /**
  36135. * Adds an uniform in the buffer.
  36136. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36137. * for the layout to be correct !
  36138. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36139. * @param {number|number[]} size Data size, or data directly.
  36140. */
  36141. UniformBuffer.prototype.addUniform = function (name, size) {
  36142. if (this._noUBO) {
  36143. return;
  36144. }
  36145. if (this._uniformLocations[name] !== undefined) {
  36146. // Already existing uniform
  36147. return;
  36148. }
  36149. // This function must be called in the order of the shader layout !
  36150. // size can be the size of the uniform, or data directly
  36151. var data;
  36152. if (size instanceof Array) {
  36153. data = size;
  36154. size = data.length;
  36155. }
  36156. else {
  36157. size = size;
  36158. data = [];
  36159. // Fill with zeros
  36160. for (var i = 0; i < size; i++) {
  36161. data.push(0);
  36162. }
  36163. }
  36164. this._fillAlignment(size);
  36165. this._uniformSizes[name] = size;
  36166. this._uniformLocations[name] = this._uniformLocationPointer;
  36167. this._uniformLocationPointer += size;
  36168. for (var i = 0; i < size; i++) {
  36169. this._data.push(data[i]);
  36170. }
  36171. this._needSync = true;
  36172. };
  36173. /**
  36174. * Wrapper for addUniform.
  36175. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36176. * @param {Matrix} mat A 4x4 matrix.
  36177. */
  36178. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36179. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36180. };
  36181. /**
  36182. * Wrapper for addUniform.
  36183. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36184. * @param {number} x
  36185. * @param {number} y
  36186. */
  36187. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36188. var temp = [x, y];
  36189. this.addUniform(name, temp);
  36190. };
  36191. /**
  36192. * Wrapper for addUniform.
  36193. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36194. * @param {number} x
  36195. * @param {number} y
  36196. * @param {number} z
  36197. */
  36198. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36199. var temp = [x, y, z];
  36200. this.addUniform(name, temp);
  36201. };
  36202. /**
  36203. * Wrapper for addUniform.
  36204. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36205. * @param {Color3} color
  36206. */
  36207. UniformBuffer.prototype.addColor3 = function (name, color) {
  36208. var temp = new Array();
  36209. color.toArray(temp);
  36210. this.addUniform(name, temp);
  36211. };
  36212. /**
  36213. * Wrapper for addUniform.
  36214. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36215. * @param {Color3} color
  36216. * @param {number} alpha
  36217. */
  36218. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36219. var temp = new Array();
  36220. color.toArray(temp);
  36221. temp.push(alpha);
  36222. this.addUniform(name, temp);
  36223. };
  36224. /**
  36225. * Wrapper for addUniform.
  36226. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36227. * @param {Vector3} vector
  36228. */
  36229. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36230. var temp = new Array();
  36231. vector.toArray(temp);
  36232. this.addUniform(name, temp);
  36233. };
  36234. /**
  36235. * Wrapper for addUniform.
  36236. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36237. */
  36238. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36239. this.addUniform(name, 12);
  36240. };
  36241. /**
  36242. * Wrapper for addUniform.
  36243. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36244. */
  36245. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36246. this.addUniform(name, 8);
  36247. };
  36248. /**
  36249. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36250. */
  36251. UniformBuffer.prototype.create = function () {
  36252. if (this._noUBO) {
  36253. return;
  36254. }
  36255. if (this._buffer) {
  36256. return; // nothing to do
  36257. }
  36258. // See spec, alignment must be filled as a vec4
  36259. this._fillAlignment(4);
  36260. this._bufferData = new Float32Array(this._data);
  36261. this._rebuild();
  36262. this._needSync = true;
  36263. };
  36264. UniformBuffer.prototype._rebuild = function () {
  36265. if (this._noUBO) {
  36266. return;
  36267. }
  36268. if (this._dynamic) {
  36269. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36270. }
  36271. else {
  36272. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36273. }
  36274. };
  36275. /**
  36276. * Updates the WebGL Uniform Buffer on the GPU.
  36277. * If the `dynamic` flag is set to true, no cache comparison is done.
  36278. * Otherwise, the buffer will be updated only if the cache differs.
  36279. */
  36280. UniformBuffer.prototype.update = function () {
  36281. if (!this._buffer) {
  36282. this.create();
  36283. return;
  36284. }
  36285. if (!this._dynamic && !this._needSync) {
  36286. return;
  36287. }
  36288. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36289. this._needSync = false;
  36290. };
  36291. /**
  36292. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36293. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36294. * @param {number[]|Float32Array} data Flattened data
  36295. * @param {number} size Size of the data.
  36296. */
  36297. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36298. var location = this._uniformLocations[uniformName];
  36299. if (location === undefined) {
  36300. if (this._buffer) {
  36301. // Cannot add an uniform if the buffer is already created
  36302. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36303. return;
  36304. }
  36305. this.addUniform(uniformName, size);
  36306. location = this._uniformLocations[uniformName];
  36307. }
  36308. if (!this._buffer) {
  36309. this.create();
  36310. }
  36311. if (!this._dynamic) {
  36312. // Cache for static uniform buffers
  36313. var changed = false;
  36314. for (var i = 0; i < size; i++) {
  36315. if (this._bufferData[location + i] !== data[i]) {
  36316. changed = true;
  36317. this._bufferData[location + i] = data[i];
  36318. }
  36319. }
  36320. this._needSync = this._needSync || changed;
  36321. }
  36322. else {
  36323. // No cache for dynamic
  36324. for (var i = 0; i < size; i++) {
  36325. this._bufferData[location + i] = data[i];
  36326. }
  36327. }
  36328. };
  36329. // Update methods
  36330. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36331. // To match std140, matrix must be realigned
  36332. for (var i = 0; i < 3; i++) {
  36333. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36334. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36335. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36336. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36337. }
  36338. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36339. };
  36340. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36341. this._currentEffect.setMatrix3x3(name, matrix);
  36342. };
  36343. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36344. this._currentEffect.setMatrix2x2(name, matrix);
  36345. };
  36346. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36347. // To match std140, matrix must be realigned
  36348. for (var i = 0; i < 2; i++) {
  36349. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36350. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36351. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36352. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36353. }
  36354. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36355. };
  36356. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36357. this._currentEffect.setFloat(name, x);
  36358. };
  36359. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36360. UniformBuffer._tempBuffer[0] = x;
  36361. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36362. };
  36363. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36364. if (suffix === void 0) { suffix = ""; }
  36365. this._currentEffect.setFloat2(name + suffix, x, y);
  36366. };
  36367. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36368. if (suffix === void 0) { suffix = ""; }
  36369. UniformBuffer._tempBuffer[0] = x;
  36370. UniformBuffer._tempBuffer[1] = y;
  36371. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36372. };
  36373. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36374. if (suffix === void 0) { suffix = ""; }
  36375. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36376. };
  36377. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36378. if (suffix === void 0) { suffix = ""; }
  36379. UniformBuffer._tempBuffer[0] = x;
  36380. UniformBuffer._tempBuffer[1] = y;
  36381. UniformBuffer._tempBuffer[2] = z;
  36382. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36383. };
  36384. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36385. if (suffix === void 0) { suffix = ""; }
  36386. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36387. };
  36388. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36389. if (suffix === void 0) { suffix = ""; }
  36390. UniformBuffer._tempBuffer[0] = x;
  36391. UniformBuffer._tempBuffer[1] = y;
  36392. UniformBuffer._tempBuffer[2] = z;
  36393. UniformBuffer._tempBuffer[3] = w;
  36394. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36395. };
  36396. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36397. this._currentEffect.setMatrix(name, mat);
  36398. };
  36399. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36400. this.updateUniform(name, mat.toArray(), 16);
  36401. };
  36402. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36403. this._currentEffect.setVector3(name, vector);
  36404. };
  36405. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36406. vector.toArray(UniformBuffer._tempBuffer);
  36407. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36408. };
  36409. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36410. this._currentEffect.setVector4(name, vector);
  36411. };
  36412. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36413. vector.toArray(UniformBuffer._tempBuffer);
  36414. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36415. };
  36416. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36417. if (suffix === void 0) { suffix = ""; }
  36418. this._currentEffect.setColor3(name + suffix, color);
  36419. };
  36420. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36421. if (suffix === void 0) { suffix = ""; }
  36422. color.toArray(UniformBuffer._tempBuffer);
  36423. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36424. };
  36425. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36426. if (suffix === void 0) { suffix = ""; }
  36427. this._currentEffect.setColor4(name + suffix, color, alpha);
  36428. };
  36429. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36430. if (suffix === void 0) { suffix = ""; }
  36431. color.toArray(UniformBuffer._tempBuffer);
  36432. UniformBuffer._tempBuffer[3] = alpha;
  36433. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36434. };
  36435. /**
  36436. * Sets a sampler uniform on the effect.
  36437. * @param {string} name Name of the sampler.
  36438. * @param {Texture} texture
  36439. */
  36440. UniformBuffer.prototype.setTexture = function (name, texture) {
  36441. this._currentEffect.setTexture(name, texture);
  36442. };
  36443. /**
  36444. * Directly updates the value of the uniform in the cache AND on the GPU.
  36445. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36446. * @param {number[]|Float32Array} data Flattened data
  36447. */
  36448. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36449. this.updateUniform(uniformName, data, data.length);
  36450. this.update();
  36451. };
  36452. /**
  36453. * Binds this uniform buffer to an effect.
  36454. * @param {Effect} effect
  36455. * @param {string} name Name of the uniform block in the shader.
  36456. */
  36457. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36458. this._currentEffect = effect;
  36459. if (this._noUBO || !this._buffer) {
  36460. return;
  36461. }
  36462. effect.bindUniformBuffer(this._buffer, name);
  36463. };
  36464. /**
  36465. * Disposes the uniform buffer.
  36466. */
  36467. UniformBuffer.prototype.dispose = function () {
  36468. if (this._noUBO) {
  36469. return;
  36470. }
  36471. var index = this._engine._uniformBuffers.indexOf(this);
  36472. if (index !== -1) {
  36473. this._engine._uniformBuffers.splice(index, 1);
  36474. }
  36475. if (!this._buffer) {
  36476. return;
  36477. }
  36478. if (this._engine._releaseBuffer(this._buffer)) {
  36479. this._buffer = null;
  36480. }
  36481. };
  36482. // Pool for avoiding memory leaks
  36483. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36484. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36485. return UniformBuffer;
  36486. }());
  36487. BABYLON.UniformBuffer = UniformBuffer;
  36488. })(BABYLON || (BABYLON = {}));
  36489. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36490. var BABYLON;
  36491. (function (BABYLON) {
  36492. /**
  36493. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36494. */
  36495. var VertexData = /** @class */ (function () {
  36496. function VertexData() {
  36497. }
  36498. /**
  36499. * Uses the passed data array to set the set the values for the specified kind of data
  36500. * @param data a linear array of floating numbers
  36501. * @param kind the type of data that is being set, eg positions, colors etc
  36502. */
  36503. VertexData.prototype.set = function (data, kind) {
  36504. switch (kind) {
  36505. case BABYLON.VertexBuffer.PositionKind:
  36506. this.positions = data;
  36507. break;
  36508. case BABYLON.VertexBuffer.NormalKind:
  36509. this.normals = data;
  36510. break;
  36511. case BABYLON.VertexBuffer.TangentKind:
  36512. this.tangents = data;
  36513. break;
  36514. case BABYLON.VertexBuffer.UVKind:
  36515. this.uvs = data;
  36516. break;
  36517. case BABYLON.VertexBuffer.UV2Kind:
  36518. this.uvs2 = data;
  36519. break;
  36520. case BABYLON.VertexBuffer.UV3Kind:
  36521. this.uvs3 = data;
  36522. break;
  36523. case BABYLON.VertexBuffer.UV4Kind:
  36524. this.uvs4 = data;
  36525. break;
  36526. case BABYLON.VertexBuffer.UV5Kind:
  36527. this.uvs5 = data;
  36528. break;
  36529. case BABYLON.VertexBuffer.UV6Kind:
  36530. this.uvs6 = data;
  36531. break;
  36532. case BABYLON.VertexBuffer.ColorKind:
  36533. this.colors = data;
  36534. break;
  36535. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36536. this.matricesIndices = data;
  36537. break;
  36538. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36539. this.matricesWeights = data;
  36540. break;
  36541. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36542. this.matricesIndicesExtra = data;
  36543. break;
  36544. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36545. this.matricesWeightsExtra = data;
  36546. break;
  36547. }
  36548. };
  36549. /**
  36550. * Associates the vertexData to the passed Mesh.
  36551. * Sets it as updatable or not (default `false`)
  36552. * @param mesh the mesh the vertexData is applied to
  36553. * @param updatable when used and having the value true allows new data to update the vertexData
  36554. * @returns the VertexData
  36555. */
  36556. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36557. this._applyTo(mesh, updatable);
  36558. return this;
  36559. };
  36560. /**
  36561. * Associates the vertexData to the passed Geometry.
  36562. * Sets it as updatable or not (default `false`)
  36563. * @param geometry the geometry the vertexData is applied to
  36564. * @param updatable when used and having the value true allows new data to update the vertexData
  36565. * @returns VertexData
  36566. */
  36567. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36568. this._applyTo(geometry, updatable);
  36569. return this;
  36570. };
  36571. /**
  36572. * Updates the associated mesh
  36573. * @param mesh the mesh to be updated
  36574. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36575. * @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
  36576. * @returns VertexData
  36577. */
  36578. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36579. this._update(mesh);
  36580. return this;
  36581. };
  36582. /**
  36583. * Updates the associated geometry
  36584. * @param geometry the geometry to be updated
  36585. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36586. * @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
  36587. * @returns VertexData.
  36588. */
  36589. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36590. this._update(geometry);
  36591. return this;
  36592. };
  36593. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36594. if (updatable === void 0) { updatable = false; }
  36595. if (this.positions) {
  36596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36597. }
  36598. if (this.normals) {
  36599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36600. }
  36601. if (this.tangents) {
  36602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36603. }
  36604. if (this.uvs) {
  36605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36606. }
  36607. if (this.uvs2) {
  36608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36609. }
  36610. if (this.uvs3) {
  36611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36612. }
  36613. if (this.uvs4) {
  36614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36615. }
  36616. if (this.uvs5) {
  36617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36618. }
  36619. if (this.uvs6) {
  36620. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36621. }
  36622. if (this.colors) {
  36623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36624. }
  36625. if (this.matricesIndices) {
  36626. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36627. }
  36628. if (this.matricesWeights) {
  36629. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36630. }
  36631. if (this.matricesIndicesExtra) {
  36632. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36633. }
  36634. if (this.matricesWeightsExtra) {
  36635. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36636. }
  36637. if (this.indices) {
  36638. meshOrGeometry.setIndices(this.indices, null, updatable);
  36639. }
  36640. else {
  36641. meshOrGeometry.setIndices([], null);
  36642. }
  36643. return this;
  36644. };
  36645. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36646. if (this.positions) {
  36647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36648. }
  36649. if (this.normals) {
  36650. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36651. }
  36652. if (this.tangents) {
  36653. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36654. }
  36655. if (this.uvs) {
  36656. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36657. }
  36658. if (this.uvs2) {
  36659. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36660. }
  36661. if (this.uvs3) {
  36662. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36663. }
  36664. if (this.uvs4) {
  36665. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36666. }
  36667. if (this.uvs5) {
  36668. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36669. }
  36670. if (this.uvs6) {
  36671. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36672. }
  36673. if (this.colors) {
  36674. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36675. }
  36676. if (this.matricesIndices) {
  36677. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36678. }
  36679. if (this.matricesWeights) {
  36680. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36681. }
  36682. if (this.matricesIndicesExtra) {
  36683. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36684. }
  36685. if (this.matricesWeightsExtra) {
  36686. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36687. }
  36688. if (this.indices) {
  36689. meshOrGeometry.setIndices(this.indices, null);
  36690. }
  36691. return this;
  36692. };
  36693. /**
  36694. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36695. * @param matrix the transforming matrix
  36696. * @returns the VertexData
  36697. */
  36698. VertexData.prototype.transform = function (matrix) {
  36699. var transformed = BABYLON.Vector3.Zero();
  36700. var index;
  36701. if (this.positions) {
  36702. var position = BABYLON.Vector3.Zero();
  36703. for (index = 0; index < this.positions.length; index += 3) {
  36704. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36705. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36706. this.positions[index] = transformed.x;
  36707. this.positions[index + 1] = transformed.y;
  36708. this.positions[index + 2] = transformed.z;
  36709. }
  36710. }
  36711. if (this.normals) {
  36712. var normal = BABYLON.Vector3.Zero();
  36713. for (index = 0; index < this.normals.length; index += 3) {
  36714. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36715. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36716. this.normals[index] = transformed.x;
  36717. this.normals[index + 1] = transformed.y;
  36718. this.normals[index + 2] = transformed.z;
  36719. }
  36720. }
  36721. if (this.tangents) {
  36722. var tangent = BABYLON.Vector4.Zero();
  36723. var tangentTransformed = BABYLON.Vector4.Zero();
  36724. for (index = 0; index < this.tangents.length; index += 4) {
  36725. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36726. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36727. this.tangents[index] = tangentTransformed.x;
  36728. this.tangents[index + 1] = tangentTransformed.y;
  36729. this.tangents[index + 2] = tangentTransformed.z;
  36730. this.tangents[index + 3] = tangentTransformed.w;
  36731. }
  36732. }
  36733. return this;
  36734. };
  36735. /**
  36736. * Merges the passed VertexData into the current one
  36737. * @param other the VertexData to be merged into the current one
  36738. * @returns the modified VertexData
  36739. */
  36740. VertexData.prototype.merge = function (other) {
  36741. this._validate();
  36742. other._validate();
  36743. if (!this.normals !== !other.normals ||
  36744. !this.tangents !== !other.tangents ||
  36745. !this.uvs !== !other.uvs ||
  36746. !this.uvs2 !== !other.uvs2 ||
  36747. !this.uvs3 !== !other.uvs3 ||
  36748. !this.uvs4 !== !other.uvs4 ||
  36749. !this.uvs5 !== !other.uvs5 ||
  36750. !this.uvs6 !== !other.uvs6 ||
  36751. !this.colors !== !other.colors ||
  36752. !this.matricesIndices !== !other.matricesIndices ||
  36753. !this.matricesWeights !== !other.matricesWeights ||
  36754. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36755. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36756. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36757. }
  36758. if (other.indices) {
  36759. if (!this.indices) {
  36760. this.indices = [];
  36761. }
  36762. var offset = this.positions ? this.positions.length / 3 : 0;
  36763. for (var index = 0; index < other.indices.length; index++) {
  36764. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36765. this.indices.push(other.indices[index] + offset);
  36766. }
  36767. }
  36768. this.positions = this._mergeElement(this.positions, other.positions);
  36769. this.normals = this._mergeElement(this.normals, other.normals);
  36770. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36771. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36772. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36773. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36774. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36775. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36776. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36777. this.colors = this._mergeElement(this.colors, other.colors);
  36778. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36779. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36780. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36781. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36782. return this;
  36783. };
  36784. VertexData.prototype._mergeElement = function (source, other) {
  36785. if (!source) {
  36786. return other;
  36787. }
  36788. if (!other) {
  36789. return source;
  36790. }
  36791. var len = other.length + source.length;
  36792. var isSrcTypedArray = source instanceof Float32Array;
  36793. var isOthTypedArray = other instanceof Float32Array;
  36794. // use non-loop method when the source is Float32Array
  36795. if (isSrcTypedArray) {
  36796. var ret32 = new Float32Array(len);
  36797. ret32.set(source);
  36798. ret32.set(other, source.length);
  36799. return ret32;
  36800. // source is number[], when other is also use concat
  36801. }
  36802. else if (!isOthTypedArray) {
  36803. return source.concat(other);
  36804. // source is a number[], but other is a Float32Array, loop required
  36805. }
  36806. else {
  36807. var ret = source.slice(0); // copy source to a separate array
  36808. for (var i = 0, len = other.length; i < len; i++) {
  36809. ret.push(other[i]);
  36810. }
  36811. return ret;
  36812. }
  36813. };
  36814. VertexData.prototype._validate = function () {
  36815. if (!this.positions) {
  36816. throw new Error("Positions are required");
  36817. }
  36818. var getElementCount = function (kind, values) {
  36819. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36820. if ((values.length % stride) !== 0) {
  36821. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36822. }
  36823. return values.length / stride;
  36824. };
  36825. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36826. var validateElementCount = function (kind, values) {
  36827. var elementCount = getElementCount(kind, values);
  36828. if (elementCount !== positionsElementCount) {
  36829. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36830. }
  36831. };
  36832. if (this.normals)
  36833. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36834. if (this.tangents)
  36835. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36836. if (this.uvs)
  36837. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36838. if (this.uvs2)
  36839. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36840. if (this.uvs3)
  36841. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36842. if (this.uvs4)
  36843. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36844. if (this.uvs5)
  36845. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36846. if (this.uvs6)
  36847. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36848. if (this.colors)
  36849. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36850. if (this.matricesIndices)
  36851. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36852. if (this.matricesWeights)
  36853. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36854. if (this.matricesIndicesExtra)
  36855. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36856. if (this.matricesWeightsExtra)
  36857. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36858. };
  36859. /**
  36860. * Serializes the VertexData
  36861. * @returns a serialized object
  36862. */
  36863. VertexData.prototype.serialize = function () {
  36864. var serializationObject = this.serialize();
  36865. if (this.positions) {
  36866. serializationObject.positions = this.positions;
  36867. }
  36868. if (this.normals) {
  36869. serializationObject.normals = this.normals;
  36870. }
  36871. if (this.tangents) {
  36872. serializationObject.tangents = this.tangents;
  36873. }
  36874. if (this.uvs) {
  36875. serializationObject.uvs = this.uvs;
  36876. }
  36877. if (this.uvs2) {
  36878. serializationObject.uvs2 = this.uvs2;
  36879. }
  36880. if (this.uvs3) {
  36881. serializationObject.uvs3 = this.uvs3;
  36882. }
  36883. if (this.uvs4) {
  36884. serializationObject.uvs4 = this.uvs4;
  36885. }
  36886. if (this.uvs5) {
  36887. serializationObject.uvs5 = this.uvs5;
  36888. }
  36889. if (this.uvs6) {
  36890. serializationObject.uvs6 = this.uvs6;
  36891. }
  36892. if (this.colors) {
  36893. serializationObject.colors = this.colors;
  36894. }
  36895. if (this.matricesIndices) {
  36896. serializationObject.matricesIndices = this.matricesIndices;
  36897. serializationObject.matricesIndices._isExpanded = true;
  36898. }
  36899. if (this.matricesWeights) {
  36900. serializationObject.matricesWeights = this.matricesWeights;
  36901. }
  36902. if (this.matricesIndicesExtra) {
  36903. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36904. serializationObject.matricesIndicesExtra._isExpanded = true;
  36905. }
  36906. if (this.matricesWeightsExtra) {
  36907. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36908. }
  36909. serializationObject.indices = this.indices;
  36910. return serializationObject;
  36911. };
  36912. // Statics
  36913. /**
  36914. * Extracts the vertexData from a mesh
  36915. * @param mesh the mesh from which to extract the VertexData
  36916. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36917. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36918. * @returns the object VertexData associated to the passed mesh
  36919. */
  36920. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36921. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36922. };
  36923. /**
  36924. * Extracts the vertexData from the geometry
  36925. * @param geometry the geometry from which to extract the VertexData
  36926. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36927. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36928. * @returns the object VertexData associated to the passed mesh
  36929. */
  36930. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36931. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36932. };
  36933. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36934. var result = new VertexData();
  36935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36936. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36937. }
  36938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36939. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36940. }
  36941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36942. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36943. }
  36944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36945. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36946. }
  36947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36948. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36949. }
  36950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36951. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36952. }
  36953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36954. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36955. }
  36956. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36957. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36958. }
  36959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36960. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36961. }
  36962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36963. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36964. }
  36965. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36966. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36967. }
  36968. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36969. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36970. }
  36971. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36972. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36973. }
  36974. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36975. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36976. }
  36977. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36978. return result;
  36979. };
  36980. /**
  36981. * Creates the VertexData for a Ribbon
  36982. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36983. * * pathArray array of paths, each of which an array of successive Vector3
  36984. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36985. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36986. * * 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
  36987. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36988. * * 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)
  36989. * * 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)
  36990. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36991. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36992. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36993. * @returns the VertexData of the ribbon
  36994. */
  36995. VertexData.CreateRibbon = function (options) {
  36996. var pathArray = options.pathArray;
  36997. var closeArray = options.closeArray || false;
  36998. var closePath = options.closePath || false;
  36999. var invertUV = options.invertUV || false;
  37000. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37001. var offset = options.offset || defaultOffset;
  37002. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37003. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37004. var customUV = options.uvs;
  37005. var customColors = options.colors;
  37006. var positions = [];
  37007. var indices = [];
  37008. var normals = [];
  37009. var uvs = [];
  37010. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37011. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37012. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37013. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37014. var minlg; // minimal length among all paths from pathArray
  37015. var lg = []; // array of path lengths : nb of vertex per path
  37016. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37017. var p; // path iterator
  37018. var i; // point iterator
  37019. var j; // point iterator
  37020. // if single path in pathArray
  37021. if (pathArray.length < 2) {
  37022. var ar1 = [];
  37023. var ar2 = [];
  37024. for (i = 0; i < pathArray[0].length - offset; i++) {
  37025. ar1.push(pathArray[0][i]);
  37026. ar2.push(pathArray[0][i + offset]);
  37027. }
  37028. pathArray = [ar1, ar2];
  37029. }
  37030. // positions and horizontal distances (u)
  37031. var idc = 0;
  37032. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37033. var path;
  37034. var l;
  37035. minlg = pathArray[0].length;
  37036. var vectlg;
  37037. var dist;
  37038. for (p = 0; p < pathArray.length; p++) {
  37039. uTotalDistance[p] = 0;
  37040. us[p] = [0];
  37041. path = pathArray[p];
  37042. l = path.length;
  37043. minlg = (minlg < l) ? minlg : l;
  37044. j = 0;
  37045. while (j < l) {
  37046. positions.push(path[j].x, path[j].y, path[j].z);
  37047. if (j > 0) {
  37048. vectlg = path[j].subtract(path[j - 1]).length();
  37049. dist = vectlg + uTotalDistance[p];
  37050. us[p].push(dist);
  37051. uTotalDistance[p] = dist;
  37052. }
  37053. j++;
  37054. }
  37055. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37056. j--;
  37057. positions.push(path[0].x, path[0].y, path[0].z);
  37058. vectlg = path[j].subtract(path[0]).length();
  37059. dist = vectlg + uTotalDistance[p];
  37060. us[p].push(dist);
  37061. uTotalDistance[p] = dist;
  37062. }
  37063. lg[p] = l + closePathCorr;
  37064. idx[p] = idc;
  37065. idc += (l + closePathCorr);
  37066. }
  37067. // vertical distances (v)
  37068. var path1;
  37069. var path2;
  37070. var vertex1 = null;
  37071. var vertex2 = null;
  37072. for (i = 0; i < minlg + closePathCorr; i++) {
  37073. vTotalDistance[i] = 0;
  37074. vs[i] = [0];
  37075. for (p = 0; p < pathArray.length - 1; p++) {
  37076. path1 = pathArray[p];
  37077. path2 = pathArray[p + 1];
  37078. if (i === minlg) { // closePath
  37079. vertex1 = path1[0];
  37080. vertex2 = path2[0];
  37081. }
  37082. else {
  37083. vertex1 = path1[i];
  37084. vertex2 = path2[i];
  37085. }
  37086. vectlg = vertex2.subtract(vertex1).length();
  37087. dist = vectlg + vTotalDistance[i];
  37088. vs[i].push(dist);
  37089. vTotalDistance[i] = dist;
  37090. }
  37091. if (closeArray && vertex2 && vertex1) {
  37092. path1 = pathArray[p];
  37093. path2 = pathArray[0];
  37094. if (i === minlg) { // closePath
  37095. vertex2 = path2[0];
  37096. }
  37097. vectlg = vertex2.subtract(vertex1).length();
  37098. dist = vectlg + vTotalDistance[i];
  37099. vTotalDistance[i] = dist;
  37100. }
  37101. }
  37102. // uvs
  37103. var u;
  37104. var v;
  37105. if (customUV) {
  37106. for (p = 0; p < customUV.length; p++) {
  37107. uvs.push(customUV[p].x, customUV[p].y);
  37108. }
  37109. }
  37110. else {
  37111. for (p = 0; p < pathArray.length; p++) {
  37112. for (i = 0; i < minlg + closePathCorr; i++) {
  37113. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37114. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37115. if (invertUV) {
  37116. uvs.push(v, u);
  37117. }
  37118. else {
  37119. uvs.push(u, v);
  37120. }
  37121. }
  37122. }
  37123. }
  37124. // indices
  37125. p = 0; // path index
  37126. var pi = 0; // positions array index
  37127. var l1 = lg[p] - 1; // path1 length
  37128. var l2 = lg[p + 1] - 1; // path2 length
  37129. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37130. var shft = idx[1] - idx[0]; // shift
  37131. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37132. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37133. // 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
  37134. indices.push(pi, pi + shft, pi + 1);
  37135. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37136. pi += 1;
  37137. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37138. p++;
  37139. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37140. shft = idx[0] - idx[p];
  37141. l1 = lg[p] - 1;
  37142. l2 = lg[0] - 1;
  37143. }
  37144. else {
  37145. shft = idx[p + 1] - idx[p];
  37146. l1 = lg[p] - 1;
  37147. l2 = lg[p + 1] - 1;
  37148. }
  37149. pi = idx[p];
  37150. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37151. }
  37152. }
  37153. // normals
  37154. VertexData.ComputeNormals(positions, indices, normals);
  37155. if (closePath) { // update both the first and last vertex normals to their average value
  37156. var indexFirst = 0;
  37157. var indexLast = 0;
  37158. for (p = 0; p < pathArray.length; p++) {
  37159. indexFirst = idx[p] * 3;
  37160. if (p + 1 < pathArray.length) {
  37161. indexLast = (idx[p + 1] - 1) * 3;
  37162. }
  37163. else {
  37164. indexLast = normals.length - 3;
  37165. }
  37166. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37167. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37168. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37169. normals[indexLast] = normals[indexFirst];
  37170. normals[indexLast + 1] = normals[indexFirst + 1];
  37171. normals[indexLast + 2] = normals[indexFirst + 2];
  37172. }
  37173. }
  37174. // sides
  37175. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37176. // Colors
  37177. var colors = null;
  37178. if (customColors) {
  37179. colors = new Float32Array(customColors.length * 4);
  37180. for (var c = 0; c < customColors.length; c++) {
  37181. colors[c * 4] = customColors[c].r;
  37182. colors[c * 4 + 1] = customColors[c].g;
  37183. colors[c * 4 + 2] = customColors[c].b;
  37184. colors[c * 4 + 3] = customColors[c].a;
  37185. }
  37186. }
  37187. // Result
  37188. var vertexData = new VertexData();
  37189. var positions32 = new Float32Array(positions);
  37190. var normals32 = new Float32Array(normals);
  37191. var uvs32 = new Float32Array(uvs);
  37192. vertexData.indices = indices;
  37193. vertexData.positions = positions32;
  37194. vertexData.normals = normals32;
  37195. vertexData.uvs = uvs32;
  37196. if (colors) {
  37197. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37198. }
  37199. if (closePath) {
  37200. vertexData._idx = idx;
  37201. }
  37202. return vertexData;
  37203. };
  37204. /**
  37205. * Creates the VertexData for a box
  37206. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37207. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37208. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37209. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37210. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37211. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37212. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37213. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37214. * * 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)
  37215. * * 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)
  37216. * @returns the VertexData of the box
  37217. */
  37218. VertexData.CreateBox = function (options) {
  37219. var normalsSource = [
  37220. new BABYLON.Vector3(0, 0, 1),
  37221. new BABYLON.Vector3(0, 0, -1),
  37222. new BABYLON.Vector3(1, 0, 0),
  37223. new BABYLON.Vector3(-1, 0, 0),
  37224. new BABYLON.Vector3(0, 1, 0),
  37225. new BABYLON.Vector3(0, -1, 0)
  37226. ];
  37227. var indices = [];
  37228. var positions = [];
  37229. var normals = [];
  37230. var uvs = [];
  37231. var width = options.width || options.size || 1;
  37232. var height = options.height || options.size || 1;
  37233. var depth = options.depth || options.size || 1;
  37234. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37235. var faceUV = options.faceUV || new Array(6);
  37236. var faceColors = options.faceColors;
  37237. var colors = [];
  37238. // default face colors and UV if undefined
  37239. for (var f = 0; f < 6; f++) {
  37240. if (faceUV[f] === undefined) {
  37241. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37242. }
  37243. if (faceColors && faceColors[f] === undefined) {
  37244. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37245. }
  37246. }
  37247. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37248. // Create each face in turn.
  37249. for (var index = 0; index < normalsSource.length; index++) {
  37250. var normal = normalsSource[index];
  37251. // Get two vectors perpendicular to the face normal and to each other.
  37252. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37253. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37254. // Six indices (two triangles) per face.
  37255. var verticesLength = positions.length / 3;
  37256. indices.push(verticesLength);
  37257. indices.push(verticesLength + 1);
  37258. indices.push(verticesLength + 2);
  37259. indices.push(verticesLength);
  37260. indices.push(verticesLength + 2);
  37261. indices.push(verticesLength + 3);
  37262. // Four vertices per face.
  37263. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37264. positions.push(vertex.x, vertex.y, vertex.z);
  37265. normals.push(normal.x, normal.y, normal.z);
  37266. uvs.push(faceUV[index].z, faceUV[index].w);
  37267. if (faceColors) {
  37268. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37269. }
  37270. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37271. positions.push(vertex.x, vertex.y, vertex.z);
  37272. normals.push(normal.x, normal.y, normal.z);
  37273. uvs.push(faceUV[index].x, faceUV[index].w);
  37274. if (faceColors) {
  37275. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37276. }
  37277. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37278. positions.push(vertex.x, vertex.y, vertex.z);
  37279. normals.push(normal.x, normal.y, normal.z);
  37280. uvs.push(faceUV[index].x, faceUV[index].y);
  37281. if (faceColors) {
  37282. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37283. }
  37284. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37285. positions.push(vertex.x, vertex.y, vertex.z);
  37286. normals.push(normal.x, normal.y, normal.z);
  37287. uvs.push(faceUV[index].z, faceUV[index].y);
  37288. if (faceColors) {
  37289. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37290. }
  37291. }
  37292. // sides
  37293. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37294. // Result
  37295. var vertexData = new VertexData();
  37296. vertexData.indices = indices;
  37297. vertexData.positions = positions;
  37298. vertexData.normals = normals;
  37299. vertexData.uvs = uvs;
  37300. if (faceColors) {
  37301. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37302. vertexData.colors = totalColors;
  37303. }
  37304. return vertexData;
  37305. };
  37306. /**
  37307. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37308. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37309. * * segments sets the number of horizontal strips optional, default 32
  37310. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37311. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37312. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37313. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37314. * * 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
  37315. * * 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
  37316. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37317. * * 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)
  37318. * * 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)
  37319. * @returns the VertexData of the ellipsoid
  37320. */
  37321. VertexData.CreateSphere = function (options) {
  37322. var segments = options.segments || 32;
  37323. var diameterX = options.diameterX || options.diameter || 1;
  37324. var diameterY = options.diameterY || options.diameter || 1;
  37325. var diameterZ = options.diameterZ || options.diameter || 1;
  37326. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37327. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37328. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37329. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37330. var totalZRotationSteps = 2 + segments;
  37331. var totalYRotationSteps = 2 * totalZRotationSteps;
  37332. var indices = [];
  37333. var positions = [];
  37334. var normals = [];
  37335. var uvs = [];
  37336. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37337. var normalizedZ = zRotationStep / totalZRotationSteps;
  37338. var angleZ = normalizedZ * Math.PI * slice;
  37339. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37340. var normalizedY = yRotationStep / totalYRotationSteps;
  37341. var angleY = normalizedY * Math.PI * 2 * arc;
  37342. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37343. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37344. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37345. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37346. var vertex = complete.multiply(radius);
  37347. var normal = complete.divide(radius).normalize();
  37348. positions.push(vertex.x, vertex.y, vertex.z);
  37349. normals.push(normal.x, normal.y, normal.z);
  37350. uvs.push(normalizedY, normalizedZ);
  37351. }
  37352. if (zRotationStep > 0) {
  37353. var verticesCount = positions.length / 3;
  37354. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37355. indices.push((firstIndex));
  37356. indices.push((firstIndex + 1));
  37357. indices.push(firstIndex + totalYRotationSteps + 1);
  37358. indices.push((firstIndex + totalYRotationSteps + 1));
  37359. indices.push((firstIndex + 1));
  37360. indices.push((firstIndex + totalYRotationSteps + 2));
  37361. }
  37362. }
  37363. }
  37364. // Sides
  37365. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37366. // Result
  37367. var vertexData = new VertexData();
  37368. vertexData.indices = indices;
  37369. vertexData.positions = positions;
  37370. vertexData.normals = normals;
  37371. vertexData.uvs = uvs;
  37372. return vertexData;
  37373. };
  37374. /**
  37375. * Creates the VertexData for a cylinder, cone or prism
  37376. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37377. * * height sets the height (y direction) of the cylinder, optional, default 2
  37378. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37379. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37380. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37381. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37382. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37383. * * 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
  37384. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37385. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37386. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37387. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37388. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37389. * * 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)
  37390. * * 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)
  37391. * @returns the VertexData of the cylinder, cone or prism
  37392. */
  37393. VertexData.CreateCylinder = function (options) {
  37394. var height = options.height || 2;
  37395. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37396. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37397. var tessellation = options.tessellation || 24;
  37398. var subdivisions = options.subdivisions || 1;
  37399. var hasRings = options.hasRings ? true : false;
  37400. var enclose = options.enclose ? true : false;
  37401. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37402. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37403. var faceUV = options.faceUV || new Array(3);
  37404. var faceColors = options.faceColors;
  37405. // default face colors and UV if undefined
  37406. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37407. var ringNb = (hasRings) ? subdivisions : 1;
  37408. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37409. var f;
  37410. for (f = 0; f < surfaceNb; f++) {
  37411. if (faceColors && faceColors[f] === undefined) {
  37412. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37413. }
  37414. }
  37415. for (f = 0; f < surfaceNb; f++) {
  37416. if (faceUV && faceUV[f] === undefined) {
  37417. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37418. }
  37419. }
  37420. var indices = new Array();
  37421. var positions = new Array();
  37422. var normals = new Array();
  37423. var uvs = new Array();
  37424. var colors = new Array();
  37425. var angle_step = Math.PI * 2 * arc / tessellation;
  37426. var angle;
  37427. var h;
  37428. var radius;
  37429. var tan = (diameterBottom - diameterTop) / 2 / height;
  37430. var ringVertex = BABYLON.Vector3.Zero();
  37431. var ringNormal = BABYLON.Vector3.Zero();
  37432. var ringFirstVertex = BABYLON.Vector3.Zero();
  37433. var ringFirstNormal = BABYLON.Vector3.Zero();
  37434. var quadNormal = BABYLON.Vector3.Zero();
  37435. var Y = BABYLON.Axis.Y;
  37436. // positions, normals, uvs
  37437. var i;
  37438. var j;
  37439. var r;
  37440. var ringIdx = 1;
  37441. var s = 1; // surface index
  37442. var cs = 0;
  37443. var v = 0;
  37444. for (i = 0; i <= subdivisions; i++) {
  37445. h = i / subdivisions;
  37446. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37447. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37448. for (r = 0; r < ringIdx; r++) {
  37449. if (hasRings) {
  37450. s += r;
  37451. }
  37452. if (enclose) {
  37453. s += 2 * r;
  37454. }
  37455. for (j = 0; j <= tessellation; j++) {
  37456. angle = j * angle_step;
  37457. // position
  37458. ringVertex.x = Math.cos(-angle) * radius;
  37459. ringVertex.y = -height / 2 + h * height;
  37460. ringVertex.z = Math.sin(-angle) * radius;
  37461. // normal
  37462. if (diameterTop === 0 && i === subdivisions) {
  37463. // if no top cap, reuse former normals
  37464. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37465. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37466. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37467. }
  37468. else {
  37469. ringNormal.x = ringVertex.x;
  37470. ringNormal.z = ringVertex.z;
  37471. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37472. ringNormal.normalize();
  37473. }
  37474. // keep first ring vertex values for enclose
  37475. if (j === 0) {
  37476. ringFirstVertex.copyFrom(ringVertex);
  37477. ringFirstNormal.copyFrom(ringNormal);
  37478. }
  37479. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37480. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37481. if (hasRings) {
  37482. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37483. }
  37484. else {
  37485. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37486. }
  37487. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37488. if (faceColors) {
  37489. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37490. }
  37491. }
  37492. // if enclose, add four vertices and their dedicated normals
  37493. if (arc !== 1 && enclose) {
  37494. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37495. positions.push(0, ringVertex.y, 0);
  37496. positions.push(0, ringVertex.y, 0);
  37497. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37498. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37499. quadNormal.normalize();
  37500. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37501. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37502. quadNormal.normalize();
  37503. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37504. if (hasRings) {
  37505. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37506. }
  37507. else {
  37508. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37509. }
  37510. uvs.push(faceUV[s + 1].x, v);
  37511. uvs.push(faceUV[s + 1].z, v);
  37512. if (hasRings) {
  37513. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37514. }
  37515. else {
  37516. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37517. }
  37518. uvs.push(faceUV[s + 2].x, v);
  37519. uvs.push(faceUV[s + 2].z, v);
  37520. if (faceColors) {
  37521. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37522. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37523. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37524. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37525. }
  37526. }
  37527. if (cs !== s) {
  37528. cs = s;
  37529. }
  37530. }
  37531. }
  37532. // indices
  37533. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37534. var s;
  37535. i = 0;
  37536. for (s = 0; s < subdivisions; s++) {
  37537. var i0 = 0;
  37538. var i1 = 0;
  37539. var i2 = 0;
  37540. var i3 = 0;
  37541. for (j = 0; j < tessellation; j++) {
  37542. i0 = i * (e + 1) + j;
  37543. i1 = (i + 1) * (e + 1) + j;
  37544. i2 = i * (e + 1) + (j + 1);
  37545. i3 = (i + 1) * (e + 1) + (j + 1);
  37546. indices.push(i0, i1, i2);
  37547. indices.push(i3, i2, i1);
  37548. }
  37549. if (arc !== 1 && enclose) { // if enclose, add two quads
  37550. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37551. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37552. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37553. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37554. }
  37555. i = (hasRings) ? (i + 2) : (i + 1);
  37556. }
  37557. // Caps
  37558. var createCylinderCap = function (isTop) {
  37559. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37560. if (radius === 0) {
  37561. return;
  37562. }
  37563. // Cap positions, normals & uvs
  37564. var angle;
  37565. var circleVector;
  37566. var i;
  37567. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37568. var c = null;
  37569. if (faceColors) {
  37570. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37571. }
  37572. // cap center
  37573. var vbase = positions.length / 3;
  37574. var offset = isTop ? height / 2 : -height / 2;
  37575. var center = new BABYLON.Vector3(0, offset, 0);
  37576. positions.push(center.x, center.y, center.z);
  37577. normals.push(0, isTop ? 1 : -1, 0);
  37578. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37579. if (c) {
  37580. colors.push(c.r, c.g, c.b, c.a);
  37581. }
  37582. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37583. for (i = 0; i <= tessellation; i++) {
  37584. angle = Math.PI * 2 * i * arc / tessellation;
  37585. var cos = Math.cos(-angle);
  37586. var sin = Math.sin(-angle);
  37587. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37588. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37589. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37590. normals.push(0, isTop ? 1 : -1, 0);
  37591. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37592. if (c) {
  37593. colors.push(c.r, c.g, c.b, c.a);
  37594. }
  37595. }
  37596. // Cap indices
  37597. for (i = 0; i < tessellation; i++) {
  37598. if (!isTop) {
  37599. indices.push(vbase);
  37600. indices.push(vbase + (i + 1));
  37601. indices.push(vbase + (i + 2));
  37602. }
  37603. else {
  37604. indices.push(vbase);
  37605. indices.push(vbase + (i + 2));
  37606. indices.push(vbase + (i + 1));
  37607. }
  37608. }
  37609. };
  37610. // add caps to geometry
  37611. createCylinderCap(false);
  37612. createCylinderCap(true);
  37613. // Sides
  37614. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37615. var vertexData = new VertexData();
  37616. vertexData.indices = indices;
  37617. vertexData.positions = positions;
  37618. vertexData.normals = normals;
  37619. vertexData.uvs = uvs;
  37620. if (faceColors) {
  37621. vertexData.colors = colors;
  37622. }
  37623. return vertexData;
  37624. };
  37625. /**
  37626. * Creates the VertexData for a torus
  37627. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37628. * * diameter the diameter of the torus, optional default 1
  37629. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37630. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37631. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37632. * * 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)
  37633. * * 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)
  37634. * @returns the VertexData of the torus
  37635. */
  37636. VertexData.CreateTorus = function (options) {
  37637. var indices = [];
  37638. var positions = [];
  37639. var normals = [];
  37640. var uvs = [];
  37641. var diameter = options.diameter || 1;
  37642. var thickness = options.thickness || 0.5;
  37643. var tessellation = options.tessellation || 16;
  37644. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37645. var stride = tessellation + 1;
  37646. for (var i = 0; i <= tessellation; i++) {
  37647. var u = i / tessellation;
  37648. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37649. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37650. for (var j = 0; j <= tessellation; j++) {
  37651. var v = 1 - j / tessellation;
  37652. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37653. var dx = Math.cos(innerAngle);
  37654. var dy = Math.sin(innerAngle);
  37655. // Create a vertex.
  37656. var normal = new BABYLON.Vector3(dx, dy, 0);
  37657. var position = normal.scale(thickness / 2);
  37658. var textureCoordinate = new BABYLON.Vector2(u, v);
  37659. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37660. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37661. positions.push(position.x, position.y, position.z);
  37662. normals.push(normal.x, normal.y, normal.z);
  37663. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37664. // And create indices for two triangles.
  37665. var nextI = (i + 1) % stride;
  37666. var nextJ = (j + 1) % stride;
  37667. indices.push(i * stride + j);
  37668. indices.push(i * stride + nextJ);
  37669. indices.push(nextI * stride + j);
  37670. indices.push(i * stride + nextJ);
  37671. indices.push(nextI * stride + nextJ);
  37672. indices.push(nextI * stride + j);
  37673. }
  37674. }
  37675. // Sides
  37676. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37677. // Result
  37678. var vertexData = new VertexData();
  37679. vertexData.indices = indices;
  37680. vertexData.positions = positions;
  37681. vertexData.normals = normals;
  37682. vertexData.uvs = uvs;
  37683. return vertexData;
  37684. };
  37685. /**
  37686. * Creates the VertexData of the LineSystem
  37687. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37688. * - lines an array of lines, each line being an array of successive Vector3
  37689. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37690. * @returns the VertexData of the LineSystem
  37691. */
  37692. VertexData.CreateLineSystem = function (options) {
  37693. var indices = [];
  37694. var positions = [];
  37695. var lines = options.lines;
  37696. var colors = options.colors;
  37697. var vertexColors = [];
  37698. var idx = 0;
  37699. for (var l = 0; l < lines.length; l++) {
  37700. var points = lines[l];
  37701. for (var index = 0; index < points.length; index++) {
  37702. positions.push(points[index].x, points[index].y, points[index].z);
  37703. if (colors) {
  37704. var color = colors[l];
  37705. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37706. }
  37707. if (index > 0) {
  37708. indices.push(idx - 1);
  37709. indices.push(idx);
  37710. }
  37711. idx++;
  37712. }
  37713. }
  37714. var vertexData = new VertexData();
  37715. vertexData.indices = indices;
  37716. vertexData.positions = positions;
  37717. if (colors) {
  37718. vertexData.colors = vertexColors;
  37719. }
  37720. return vertexData;
  37721. };
  37722. /**
  37723. * Create the VertexData for a DashedLines
  37724. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37725. * - points an array successive Vector3
  37726. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37727. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37728. * - dashNb the intended total number of dashes, optional, default 200
  37729. * @returns the VertexData for the DashedLines
  37730. */
  37731. VertexData.CreateDashedLines = function (options) {
  37732. var dashSize = options.dashSize || 3;
  37733. var gapSize = options.gapSize || 1;
  37734. var dashNb = options.dashNb || 200;
  37735. var points = options.points;
  37736. var positions = new Array();
  37737. var indices = new Array();
  37738. var curvect = BABYLON.Vector3.Zero();
  37739. var lg = 0;
  37740. var nb = 0;
  37741. var shft = 0;
  37742. var dashshft = 0;
  37743. var curshft = 0;
  37744. var idx = 0;
  37745. var i = 0;
  37746. for (i = 0; i < points.length - 1; i++) {
  37747. points[i + 1].subtractToRef(points[i], curvect);
  37748. lg += curvect.length();
  37749. }
  37750. shft = lg / dashNb;
  37751. dashshft = dashSize * shft / (dashSize + gapSize);
  37752. for (i = 0; i < points.length - 1; i++) {
  37753. points[i + 1].subtractToRef(points[i], curvect);
  37754. nb = Math.floor(curvect.length() / shft);
  37755. curvect.normalize();
  37756. for (var j = 0; j < nb; j++) {
  37757. curshft = shft * j;
  37758. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37759. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37760. indices.push(idx, idx + 1);
  37761. idx += 2;
  37762. }
  37763. }
  37764. // Result
  37765. var vertexData = new VertexData();
  37766. vertexData.positions = positions;
  37767. vertexData.indices = indices;
  37768. return vertexData;
  37769. };
  37770. /**
  37771. * Creates the VertexData for a Ground
  37772. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37773. * - width the width (x direction) of the ground, optional, default 1
  37774. * - height the height (z direction) of the ground, optional, default 1
  37775. * - subdivisions the number of subdivisions per side, optional, default 1
  37776. * @returns the VertexData of the Ground
  37777. */
  37778. VertexData.CreateGround = function (options) {
  37779. var indices = [];
  37780. var positions = [];
  37781. var normals = [];
  37782. var uvs = [];
  37783. var row, col;
  37784. var width = options.width || 1;
  37785. var height = options.height || 1;
  37786. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37787. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37788. for (row = 0; row <= subdivisionsY; row++) {
  37789. for (col = 0; col <= subdivisionsX; col++) {
  37790. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37791. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37792. positions.push(position.x, position.y, position.z);
  37793. normals.push(normal.x, normal.y, normal.z);
  37794. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37795. }
  37796. }
  37797. for (row = 0; row < subdivisionsY; row++) {
  37798. for (col = 0; col < subdivisionsX; col++) {
  37799. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37800. indices.push(col + 1 + row * (subdivisionsX + 1));
  37801. indices.push(col + row * (subdivisionsX + 1));
  37802. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37803. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37804. indices.push(col + row * (subdivisionsX + 1));
  37805. }
  37806. }
  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. /**
  37816. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37817. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37818. * * xmin the ground minimum X coordinate, optional, default -1
  37819. * * zmin the ground minimum Z coordinate, optional, default -1
  37820. * * xmax the ground maximum X coordinate, optional, default 1
  37821. * * zmax the ground maximum Z coordinate, optional, default 1
  37822. * * 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}
  37823. * * 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}
  37824. * @returns the VertexData of the TiledGround
  37825. */
  37826. VertexData.CreateTiledGround = function (options) {
  37827. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37828. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37829. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37830. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37831. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37832. var precision = options.precision || { w: 1, h: 1 };
  37833. var indices = new Array();
  37834. var positions = new Array();
  37835. var normals = new Array();
  37836. var uvs = new Array();
  37837. var row, col, tileRow, tileCol;
  37838. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37839. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37840. precision.w = (precision.w < 1) ? 1 : precision.w;
  37841. precision.h = (precision.h < 1) ? 1 : precision.h;
  37842. var tileSize = {
  37843. 'w': (xmax - xmin) / subdivisions.w,
  37844. 'h': (zmax - zmin) / subdivisions.h
  37845. };
  37846. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37847. // Indices
  37848. var base = positions.length / 3;
  37849. var rowLength = precision.w + 1;
  37850. for (row = 0; row < precision.h; row++) {
  37851. for (col = 0; col < precision.w; col++) {
  37852. var square = [
  37853. base + col + row * rowLength,
  37854. base + (col + 1) + row * rowLength,
  37855. base + (col + 1) + (row + 1) * rowLength,
  37856. base + col + (row + 1) * rowLength
  37857. ];
  37858. indices.push(square[1]);
  37859. indices.push(square[2]);
  37860. indices.push(square[3]);
  37861. indices.push(square[0]);
  37862. indices.push(square[1]);
  37863. indices.push(square[3]);
  37864. }
  37865. }
  37866. // Position, normals and uvs
  37867. var position = BABYLON.Vector3.Zero();
  37868. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37869. for (row = 0; row <= precision.h; row++) {
  37870. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37871. for (col = 0; col <= precision.w; col++) {
  37872. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37873. position.y = 0;
  37874. positions.push(position.x, position.y, position.z);
  37875. normals.push(normal.x, normal.y, normal.z);
  37876. uvs.push(col / precision.w, row / precision.h);
  37877. }
  37878. }
  37879. }
  37880. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37881. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37882. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37883. }
  37884. }
  37885. // Result
  37886. var vertexData = new VertexData();
  37887. vertexData.indices = indices;
  37888. vertexData.positions = positions;
  37889. vertexData.normals = normals;
  37890. vertexData.uvs = uvs;
  37891. return vertexData;
  37892. };
  37893. /**
  37894. * Creates the VertexData of the Ground designed from a heightmap
  37895. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37896. * * width the width (x direction) of the ground
  37897. * * height the height (z direction) of the ground
  37898. * * subdivisions the number of subdivisions per side
  37899. * * minHeight the minimum altitude on the ground, optional, default 0
  37900. * * maxHeight the maximum altitude on the ground, optional default 1
  37901. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37902. * * buffer the array holding the image color data
  37903. * * bufferWidth the width of image
  37904. * * bufferHeight the height of image
  37905. * @returns the VertexData of the Ground designed from a heightmap
  37906. */
  37907. VertexData.CreateGroundFromHeightMap = function (options) {
  37908. var indices = [];
  37909. var positions = [];
  37910. var normals = [];
  37911. var uvs = [];
  37912. var row, col;
  37913. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37914. // Vertices
  37915. for (row = 0; row <= options.subdivisions; row++) {
  37916. for (col = 0; col <= options.subdivisions; col++) {
  37917. 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));
  37918. // Compute height
  37919. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37920. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37921. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37922. var r = options.buffer[pos] / 255.0;
  37923. var g = options.buffer[pos + 1] / 255.0;
  37924. var b = options.buffer[pos + 2] / 255.0;
  37925. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37926. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37927. // Add vertex
  37928. positions.push(position.x, position.y, position.z);
  37929. normals.push(0, 0, 0);
  37930. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37931. }
  37932. }
  37933. // Indices
  37934. for (row = 0; row < options.subdivisions; row++) {
  37935. for (col = 0; col < options.subdivisions; col++) {
  37936. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37937. indices.push(col + 1 + row * (options.subdivisions + 1));
  37938. indices.push(col + row * (options.subdivisions + 1));
  37939. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37940. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37941. indices.push(col + row * (options.subdivisions + 1));
  37942. }
  37943. }
  37944. // Normals
  37945. VertexData.ComputeNormals(positions, indices, normals);
  37946. // Result
  37947. var vertexData = new VertexData();
  37948. vertexData.indices = indices;
  37949. vertexData.positions = positions;
  37950. vertexData.normals = normals;
  37951. vertexData.uvs = uvs;
  37952. return vertexData;
  37953. };
  37954. /**
  37955. * Creates the VertexData for a Plane
  37956. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37957. * * size sets the width and height of the plane to the value of size, optional default 1
  37958. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37959. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37960. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37961. * * 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)
  37962. * * 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)
  37963. * @returns the VertexData of the box
  37964. */
  37965. VertexData.CreatePlane = function (options) {
  37966. var indices = [];
  37967. var positions = [];
  37968. var normals = [];
  37969. var uvs = [];
  37970. var width = options.width || options.size || 1;
  37971. var height = options.height || options.size || 1;
  37972. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37973. // Vertices
  37974. var halfWidth = width / 2.0;
  37975. var halfHeight = height / 2.0;
  37976. positions.push(-halfWidth, -halfHeight, 0);
  37977. normals.push(0, 0, -1.0);
  37978. uvs.push(0.0, 0.0);
  37979. positions.push(halfWidth, -halfHeight, 0);
  37980. normals.push(0, 0, -1.0);
  37981. uvs.push(1.0, 0.0);
  37982. positions.push(halfWidth, halfHeight, 0);
  37983. normals.push(0, 0, -1.0);
  37984. uvs.push(1.0, 1.0);
  37985. positions.push(-halfWidth, halfHeight, 0);
  37986. normals.push(0, 0, -1.0);
  37987. uvs.push(0.0, 1.0);
  37988. // Indices
  37989. indices.push(0);
  37990. indices.push(1);
  37991. indices.push(2);
  37992. indices.push(0);
  37993. indices.push(2);
  37994. indices.push(3);
  37995. // Sides
  37996. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37997. // Result
  37998. var vertexData = new VertexData();
  37999. vertexData.indices = indices;
  38000. vertexData.positions = positions;
  38001. vertexData.normals = normals;
  38002. vertexData.uvs = uvs;
  38003. return vertexData;
  38004. };
  38005. /**
  38006. * Creates the VertexData of the Disc or regular Polygon
  38007. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38008. * * radius the radius of the disc, optional default 0.5
  38009. * * tessellation the number of polygon sides, optional, default 64
  38010. * * 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
  38011. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38012. * * 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)
  38013. * * 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)
  38014. * @returns the VertexData of the box
  38015. */
  38016. VertexData.CreateDisc = function (options) {
  38017. var positions = new Array();
  38018. var indices = new Array();
  38019. var normals = new Array();
  38020. var uvs = new Array();
  38021. var radius = options.radius || 0.5;
  38022. var tessellation = options.tessellation || 64;
  38023. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38024. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38025. // positions and uvs
  38026. positions.push(0, 0, 0); // disc center first
  38027. uvs.push(0.5, 0.5);
  38028. var theta = Math.PI * 2 * arc;
  38029. var step = theta / tessellation;
  38030. for (var a = 0; a < theta; a += step) {
  38031. var x = Math.cos(a);
  38032. var y = Math.sin(a);
  38033. var u = (x + 1) / 2;
  38034. var v = (1 - y) / 2;
  38035. positions.push(radius * x, radius * y, 0);
  38036. uvs.push(u, v);
  38037. }
  38038. if (arc === 1) {
  38039. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38040. uvs.push(uvs[2], uvs[3]);
  38041. }
  38042. //indices
  38043. var vertexNb = positions.length / 3;
  38044. for (var i = 1; i < vertexNb - 1; i++) {
  38045. indices.push(i + 1, 0, i);
  38046. }
  38047. // result
  38048. VertexData.ComputeNormals(positions, indices, normals);
  38049. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38050. var vertexData = new VertexData();
  38051. vertexData.indices = indices;
  38052. vertexData.positions = positions;
  38053. vertexData.normals = normals;
  38054. vertexData.uvs = uvs;
  38055. return vertexData;
  38056. };
  38057. /**
  38058. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38059. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38060. * @param polygon a mesh built from polygonTriangulation.build()
  38061. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38062. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38063. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38064. * @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)
  38065. * @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)
  38066. * @returns the VertexData of the Polygon
  38067. */
  38068. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38069. var faceUV = fUV || new Array(3);
  38070. var faceColors = fColors;
  38071. var colors = [];
  38072. // default face colors and UV if undefined
  38073. for (var f = 0; f < 3; f++) {
  38074. if (faceUV[f] === undefined) {
  38075. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38076. }
  38077. if (faceColors && faceColors[f] === undefined) {
  38078. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38079. }
  38080. }
  38081. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38082. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38083. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38084. var indices = polygon.getIndices();
  38085. // set face colours and textures
  38086. var idx = 0;
  38087. var face = 0;
  38088. for (var index = 0; index < normals.length; index += 3) {
  38089. //Edge Face no. 1
  38090. if (Math.abs(normals[index + 1]) < 0.001) {
  38091. face = 1;
  38092. }
  38093. //Top Face no. 0
  38094. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38095. face = 0;
  38096. }
  38097. //Bottom Face no. 2
  38098. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38099. face = 2;
  38100. }
  38101. idx = index / 3;
  38102. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38103. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38104. if (faceColors) {
  38105. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38106. }
  38107. }
  38108. // sides
  38109. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38110. // Result
  38111. var vertexData = new VertexData();
  38112. vertexData.indices = indices;
  38113. vertexData.positions = positions;
  38114. vertexData.normals = normals;
  38115. vertexData.uvs = uvs;
  38116. if (faceColors) {
  38117. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38118. vertexData.colors = totalColors;
  38119. }
  38120. return vertexData;
  38121. };
  38122. /**
  38123. * Creates the VertexData of the IcoSphere
  38124. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38125. * * radius the radius of the IcoSphere, optional default 1
  38126. * * radiusX allows stretching in the x direction, optional, default radius
  38127. * * radiusY allows stretching in the y direction, optional, default radius
  38128. * * radiusZ allows stretching in the z direction, optional, default radius
  38129. * * flat when true creates a flat shaded mesh, optional, default true
  38130. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38131. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38132. * * 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)
  38133. * * 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)
  38134. * @returns the VertexData of the IcoSphere
  38135. */
  38136. VertexData.CreateIcoSphere = function (options) {
  38137. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38138. var radius = options.radius || 1;
  38139. var flat = (options.flat === undefined) ? true : options.flat;
  38140. var subdivisions = options.subdivisions || 4;
  38141. var radiusX = options.radiusX || radius;
  38142. var radiusY = options.radiusY || radius;
  38143. var radiusZ = options.radiusZ || radius;
  38144. var t = (1 + Math.sqrt(5)) / 2;
  38145. // 12 vertex x,y,z
  38146. var ico_vertices = [
  38147. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38148. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38149. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38150. ];
  38151. // index of 3 vertex makes a face of icopshere
  38152. var ico_indices = [
  38153. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38154. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38155. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38156. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38157. ];
  38158. // vertex for uv have aliased position, not for UV
  38159. var vertices_unalias_id = [
  38160. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38161. // vertex alias
  38162. 0,
  38163. 2,
  38164. 3,
  38165. 3,
  38166. 3,
  38167. 4,
  38168. 7,
  38169. 8,
  38170. 9,
  38171. 9,
  38172. 10,
  38173. 11 // 23: B + 12
  38174. ];
  38175. // uv as integer step (not pixels !)
  38176. var ico_vertexuv = [
  38177. 5, 1, 3, 1, 6, 4, 0, 0,
  38178. 5, 3, 4, 2, 2, 2, 4, 0,
  38179. 2, 0, 1, 1, 6, 0, 6, 2,
  38180. // vertex alias (for same vertex on different faces)
  38181. 0, 4,
  38182. 3, 3,
  38183. 4, 4,
  38184. 3, 1,
  38185. 4, 2,
  38186. 4, 4,
  38187. 0, 2,
  38188. 1, 1,
  38189. 2, 2,
  38190. 3, 3,
  38191. 1, 3,
  38192. 2, 4 // 23: B + 12
  38193. ];
  38194. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38195. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38196. // First island of uv mapping
  38197. // v = 4h 3+ 2
  38198. // v = 3h 9+ 4
  38199. // v = 2h 9+ 5 B
  38200. // v = 1h 9 1 0
  38201. // v = 0h 3 8 7 A
  38202. // u = 0 1 2 3 4 5 6 *a
  38203. // Second island of uv mapping
  38204. // v = 4h 0+ B+ 4+
  38205. // v = 3h A+ 2+
  38206. // v = 2h 7+ 6 3+
  38207. // v = 1h 8+ 3+
  38208. // v = 0h
  38209. // u = 0 1 2 3 4 5 6 *a
  38210. // Face layout on texture UV mapping
  38211. // ============
  38212. // \ 4 /\ 16 / ======
  38213. // \ / \ / /\ 11 /
  38214. // \/ 7 \/ / \ /
  38215. // ======= / 10 \/
  38216. // /\ 17 /\ =======
  38217. // / \ / \ \ 15 /\
  38218. // / 8 \/ 12 \ \ / \
  38219. // ============ \/ 6 \
  38220. // \ 18 /\ ============
  38221. // \ / \ \ 5 /\ 0 /
  38222. // \/ 13 \ \ / \ /
  38223. // ======= \/ 1 \/
  38224. // =============
  38225. // /\ 19 /\ 2 /\
  38226. // / \ / \ / \
  38227. // / 14 \/ 9 \/ 3 \
  38228. // ===================
  38229. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38230. var ustep = 138 / 1024;
  38231. var vstep = 239 / 1024;
  38232. var uoffset = 60 / 1024;
  38233. var voffset = 26 / 1024;
  38234. // Second island should have margin, not to touch the first island
  38235. // avoid any borderline artefact in pixel rounding
  38236. var island_u_offset = -40 / 1024;
  38237. var island_v_offset = +20 / 1024;
  38238. // face is either island 0 or 1 :
  38239. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38240. var island = [
  38241. 0, 0, 0, 0, 1,
  38242. 0, 0, 1, 1, 0,
  38243. 0, 0, 1, 1, 0,
  38244. 0, 1, 1, 1, 0 // 15 - 19
  38245. ];
  38246. var indices = new Array();
  38247. var positions = new Array();
  38248. var normals = new Array();
  38249. var uvs = new Array();
  38250. var current_indice = 0;
  38251. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38252. var face_vertex_pos = new Array(3);
  38253. var face_vertex_uv = new Array(3);
  38254. var v012;
  38255. for (v012 = 0; v012 < 3; v012++) {
  38256. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38257. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38258. }
  38259. // create all with normals
  38260. for (var face = 0; face < 20; face++) {
  38261. // 3 vertex per face
  38262. for (v012 = 0; v012 < 3; v012++) {
  38263. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38264. var v_id = ico_indices[3 * face + v012];
  38265. // vertex have 3D position (x,y,z)
  38266. 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]);
  38267. // Normalize to get normal, then scale to radius
  38268. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38269. // uv Coordinates from vertex ID
  38270. 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);
  38271. }
  38272. // Subdivide the face (interpolate pos, norm, uv)
  38273. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38274. // - norm is linear interpolation of vertex corner normal
  38275. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38276. // - uv is linear interpolation
  38277. //
  38278. // Topology is as below for sub-divide by 2
  38279. // vertex shown as v0,v1,v2
  38280. // interp index is i1 to progress in range [v0,v1[
  38281. // interp index is i2 to progress in range [v0,v2[
  38282. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38283. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38284. //
  38285. //
  38286. // i2 v2
  38287. // ^ ^
  38288. // / / \
  38289. // / / \
  38290. // / / \
  38291. // / / (0,1) \
  38292. // / #---------\
  38293. // / / \ (0,0)'/ \
  38294. // / / \ / \
  38295. // / / \ / \
  38296. // / / (0,0) \ / (1,0) \
  38297. // / #---------#---------\
  38298. // v0 v1
  38299. //
  38300. // --------------------> i1
  38301. //
  38302. // interp of (i1,i2):
  38303. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38304. // along i1 : lerp(x0,x1, i1/(S-i2))
  38305. //
  38306. // centroid of triangle is needed to get help normal computation
  38307. // (c1,c2) are used for centroid location
  38308. var interp_vertex = function (i1, i2, c1, c2) {
  38309. // vertex is interpolated from
  38310. // - face_vertex_pos[0..2]
  38311. // - face_vertex_uv[0..2]
  38312. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38313. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38314. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38315. pos_interp.normalize();
  38316. var vertex_normal;
  38317. if (flat) {
  38318. // in flat mode, recalculate normal as face centroid normal
  38319. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38320. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38321. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38322. }
  38323. else {
  38324. // in smooth mode, recalculate normal from each single vertex position
  38325. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38326. }
  38327. // Vertex normal need correction due to X,Y,Z radius scaling
  38328. vertex_normal.x /= radiusX;
  38329. vertex_normal.y /= radiusY;
  38330. vertex_normal.z /= radiusZ;
  38331. vertex_normal.normalize();
  38332. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38333. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38334. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38335. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38336. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38337. uvs.push(uv_interp.x, uv_interp.y);
  38338. // push each vertex has member of a face
  38339. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38340. indices.push(current_indice);
  38341. current_indice++;
  38342. };
  38343. for (var i2 = 0; i2 < subdivisions; i2++) {
  38344. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38345. // face : (i1,i2) for /\ :
  38346. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38347. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38348. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38349. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38350. if (i1 + i2 + 1 < subdivisions) {
  38351. // face : (i1,i2)' for \/ :
  38352. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38353. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38354. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38355. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38356. }
  38357. }
  38358. }
  38359. }
  38360. // Sides
  38361. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38362. // Result
  38363. var vertexData = new VertexData();
  38364. vertexData.indices = indices;
  38365. vertexData.positions = positions;
  38366. vertexData.normals = normals;
  38367. vertexData.uvs = uvs;
  38368. return vertexData;
  38369. };
  38370. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38371. /**
  38372. * Creates the VertexData for a Polyhedron
  38373. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38374. * * type provided types are:
  38375. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38376. * * 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)
  38377. * * size the size of the IcoSphere, optional default 1
  38378. * * sizeX allows stretching in the x direction, optional, default size
  38379. * * sizeY allows stretching in the y direction, optional, default size
  38380. * * sizeZ allows stretching in the z direction, optional, default size
  38381. * * 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
  38382. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38383. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38384. * * flat when true creates a flat shaded mesh, optional, default true
  38385. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38386. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38387. * * 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)
  38388. * * 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)
  38389. * @returns the VertexData of the Polyhedron
  38390. */
  38391. VertexData.CreatePolyhedron = function (options) {
  38392. // provided polyhedron types :
  38393. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38394. // 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)
  38395. var polyhedra = [];
  38396. 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]] };
  38397. 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]] };
  38398. polyhedra[2] = {
  38399. 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]],
  38400. 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]]
  38401. };
  38402. polyhedra[3] = {
  38403. 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]],
  38404. 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]]
  38405. };
  38406. polyhedra[4] = {
  38407. 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]],
  38408. 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]]
  38409. };
  38410. 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]] };
  38411. 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]] };
  38412. 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]] };
  38413. 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]] };
  38414. 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]] };
  38415. 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]] };
  38416. 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]] };
  38417. 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]] };
  38418. 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]] };
  38419. polyhedra[14] = {
  38420. 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]],
  38421. 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]]
  38422. };
  38423. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38424. var size = options.size;
  38425. var sizeX = options.sizeX || size || 1;
  38426. var sizeY = options.sizeY || size || 1;
  38427. var sizeZ = options.sizeZ || size || 1;
  38428. var data = options.custom || polyhedra[type];
  38429. var nbfaces = data.face.length;
  38430. var faceUV = options.faceUV || new Array(nbfaces);
  38431. var faceColors = options.faceColors;
  38432. var flat = (options.flat === undefined) ? true : options.flat;
  38433. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38434. var positions = new Array();
  38435. var indices = new Array();
  38436. var normals = new Array();
  38437. var uvs = new Array();
  38438. var colors = new Array();
  38439. var index = 0;
  38440. var faceIdx = 0; // face cursor in the array "indexes"
  38441. var indexes = new Array();
  38442. var i = 0;
  38443. var f = 0;
  38444. var u, v, ang, x, y, tmp;
  38445. // default face colors and UV if undefined
  38446. if (flat) {
  38447. for (f = 0; f < nbfaces; f++) {
  38448. if (faceColors && faceColors[f] === undefined) {
  38449. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38450. }
  38451. if (faceUV && faceUV[f] === undefined) {
  38452. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38453. }
  38454. }
  38455. }
  38456. if (!flat) {
  38457. for (i = 0; i < data.vertex.length; i++) {
  38458. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38459. uvs.push(0, 0);
  38460. }
  38461. for (f = 0; f < nbfaces; f++) {
  38462. for (i = 0; i < data.face[f].length - 2; i++) {
  38463. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38464. }
  38465. }
  38466. }
  38467. else {
  38468. for (f = 0; f < nbfaces; f++) {
  38469. var fl = data.face[f].length; // number of vertices of the current face
  38470. ang = 2 * Math.PI / fl;
  38471. x = 0.5 * Math.tan(ang / 2);
  38472. y = 0.5;
  38473. // positions, uvs, colors
  38474. for (i = 0; i < fl; i++) {
  38475. // positions
  38476. 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);
  38477. indexes.push(index);
  38478. index++;
  38479. // uvs
  38480. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38481. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38482. uvs.push(u, v);
  38483. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38484. y = x * Math.sin(ang) + y * Math.cos(ang);
  38485. x = tmp;
  38486. // colors
  38487. if (faceColors) {
  38488. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38489. }
  38490. }
  38491. // indices from indexes
  38492. for (i = 0; i < fl - 2; i++) {
  38493. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38494. }
  38495. faceIdx += fl;
  38496. }
  38497. }
  38498. VertexData.ComputeNormals(positions, indices, normals);
  38499. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38500. var vertexData = new VertexData();
  38501. vertexData.positions = positions;
  38502. vertexData.indices = indices;
  38503. vertexData.normals = normals;
  38504. vertexData.uvs = uvs;
  38505. if (faceColors && flat) {
  38506. vertexData.colors = colors;
  38507. }
  38508. return vertexData;
  38509. };
  38510. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38511. /**
  38512. * Creates the VertexData for a TorusKnot
  38513. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38514. * * radius the radius of the torus knot, optional, default 2
  38515. * * tube the thickness of the tube, optional, default 0.5
  38516. * * radialSegments the number of sides on each tube segments, optional, default 32
  38517. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38518. * * p the number of windings around the z axis, optional, default 2
  38519. * * q the number of windings around the x axis, optional, default 3
  38520. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38521. * * 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)
  38522. * * 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)
  38523. * @returns the VertexData of the Torus Knot
  38524. */
  38525. VertexData.CreateTorusKnot = function (options) {
  38526. var indices = new Array();
  38527. var positions = new Array();
  38528. var normals = new Array();
  38529. var uvs = new Array();
  38530. var radius = options.radius || 2;
  38531. var tube = options.tube || 0.5;
  38532. var radialSegments = options.radialSegments || 32;
  38533. var tubularSegments = options.tubularSegments || 32;
  38534. var p = options.p || 2;
  38535. var q = options.q || 3;
  38536. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38537. // Helper
  38538. var getPos = function (angle) {
  38539. var cu = Math.cos(angle);
  38540. var su = Math.sin(angle);
  38541. var quOverP = q / p * angle;
  38542. var cs = Math.cos(quOverP);
  38543. var tx = radius * (2 + cs) * 0.5 * cu;
  38544. var ty = radius * (2 + cs) * su * 0.5;
  38545. var tz = radius * Math.sin(quOverP) * 0.5;
  38546. return new BABYLON.Vector3(tx, ty, tz);
  38547. };
  38548. // Vertices
  38549. var i;
  38550. var j;
  38551. for (i = 0; i <= radialSegments; i++) {
  38552. var modI = i % radialSegments;
  38553. var u = modI / radialSegments * 2 * p * Math.PI;
  38554. var p1 = getPos(u);
  38555. var p2 = getPos(u + 0.01);
  38556. var tang = p2.subtract(p1);
  38557. var n = p2.add(p1);
  38558. var bitan = BABYLON.Vector3.Cross(tang, n);
  38559. n = BABYLON.Vector3.Cross(bitan, tang);
  38560. bitan.normalize();
  38561. n.normalize();
  38562. for (j = 0; j < tubularSegments; j++) {
  38563. var modJ = j % tubularSegments;
  38564. var v = modJ / tubularSegments * 2 * Math.PI;
  38565. var cx = -tube * Math.cos(v);
  38566. var cy = tube * Math.sin(v);
  38567. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38568. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38569. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38570. uvs.push(i / radialSegments);
  38571. uvs.push(j / tubularSegments);
  38572. }
  38573. }
  38574. for (i = 0; i < radialSegments; i++) {
  38575. for (j = 0; j < tubularSegments; j++) {
  38576. var jNext = (j + 1) % tubularSegments;
  38577. var a = i * tubularSegments + j;
  38578. var b = (i + 1) * tubularSegments + j;
  38579. var c = (i + 1) * tubularSegments + jNext;
  38580. var d = i * tubularSegments + jNext;
  38581. indices.push(d);
  38582. indices.push(b);
  38583. indices.push(a);
  38584. indices.push(d);
  38585. indices.push(c);
  38586. indices.push(b);
  38587. }
  38588. }
  38589. // Normals
  38590. VertexData.ComputeNormals(positions, indices, normals);
  38591. // Sides
  38592. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38593. // Result
  38594. var vertexData = new VertexData();
  38595. vertexData.indices = indices;
  38596. vertexData.positions = positions;
  38597. vertexData.normals = normals;
  38598. vertexData.uvs = uvs;
  38599. return vertexData;
  38600. };
  38601. // Tools
  38602. /**
  38603. * Compute normals for given positions and indices
  38604. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38605. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38606. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38607. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38608. * * facetNormals : optional array of facet normals (vector3)
  38609. * * facetPositions : optional array of facet positions (vector3)
  38610. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38611. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38612. * * bInfo : optional bounding info, required for facetPartitioning computation
  38613. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38614. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38615. * * useRightHandedSystem: optional boolean to for right handed system computation
  38616. * * depthSort : optional boolean to enable the facet depth sort computation
  38617. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38618. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38619. */
  38620. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38621. // temporary scalar variables
  38622. var index = 0; // facet index
  38623. var p1p2x = 0.0; // p1p2 vector x coordinate
  38624. var p1p2y = 0.0; // p1p2 vector y coordinate
  38625. var p1p2z = 0.0; // p1p2 vector z coordinate
  38626. var p3p2x = 0.0; // p3p2 vector x coordinate
  38627. var p3p2y = 0.0; // p3p2 vector y coordinate
  38628. var p3p2z = 0.0; // p3p2 vector z coordinate
  38629. var faceNormalx = 0.0; // facet normal x coordinate
  38630. var faceNormaly = 0.0; // facet normal y coordinate
  38631. var faceNormalz = 0.0; // facet normal z coordinate
  38632. var length = 0.0; // facet normal length before normalization
  38633. var v1x = 0; // vector1 x index in the positions array
  38634. var v1y = 0; // vector1 y index in the positions array
  38635. var v1z = 0; // vector1 z index in the positions array
  38636. var v2x = 0; // vector2 x index in the positions array
  38637. var v2y = 0; // vector2 y index in the positions array
  38638. var v2z = 0; // vector2 z index in the positions array
  38639. var v3x = 0; // vector3 x index in the positions array
  38640. var v3y = 0; // vector3 y index in the positions array
  38641. var v3z = 0; // vector3 z index in the positions array
  38642. var computeFacetNormals = false;
  38643. var computeFacetPositions = false;
  38644. var computeFacetPartitioning = false;
  38645. var computeDepthSort = false;
  38646. var faceNormalSign = 1;
  38647. var ratio = 0;
  38648. var distanceTo = null;
  38649. if (options) {
  38650. computeFacetNormals = (options.facetNormals) ? true : false;
  38651. computeFacetPositions = (options.facetPositions) ? true : false;
  38652. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38653. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38654. ratio = options.ratio || 0;
  38655. computeDepthSort = (options.depthSort) ? true : false;
  38656. distanceTo = (options.distanceTo);
  38657. if (computeDepthSort) {
  38658. if (distanceTo === undefined) {
  38659. distanceTo = BABYLON.Vector3.Zero();
  38660. }
  38661. var depthSortedFacets = options.depthSortedFacets;
  38662. }
  38663. }
  38664. // facetPartitioning reinit if needed
  38665. var xSubRatio = 0;
  38666. var ySubRatio = 0;
  38667. var zSubRatio = 0;
  38668. var subSq = 0;
  38669. if (computeFacetPartitioning && options && options.bbSize) {
  38670. var ox = 0; // X partitioning index for facet position
  38671. var oy = 0; // Y partinioning index for facet position
  38672. var oz = 0; // Z partinioning index for facet position
  38673. var b1x = 0; // X partitioning index for facet v1 vertex
  38674. var b1y = 0; // Y partitioning index for facet v1 vertex
  38675. var b1z = 0; // z partitioning index for facet v1 vertex
  38676. var b2x = 0; // X partitioning index for facet v2 vertex
  38677. var b2y = 0; // Y partitioning index for facet v2 vertex
  38678. var b2z = 0; // Z partitioning index for facet v2 vertex
  38679. var b3x = 0; // X partitioning index for facet v3 vertex
  38680. var b3y = 0; // Y partitioning index for facet v3 vertex
  38681. var b3z = 0; // Z partitioning index for facet v3 vertex
  38682. var block_idx_o = 0; // facet barycenter block index
  38683. var block_idx_v1 = 0; // v1 vertex block index
  38684. var block_idx_v2 = 0; // v2 vertex block index
  38685. var block_idx_v3 = 0; // v3 vertex block index
  38686. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38687. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38688. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38689. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38690. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38691. subSq = options.subDiv.max * options.subDiv.max;
  38692. options.facetPartitioning.length = 0;
  38693. }
  38694. // reset the normals
  38695. for (index = 0; index < positions.length; index++) {
  38696. normals[index] = 0.0;
  38697. }
  38698. // Loop : 1 indice triplet = 1 facet
  38699. var nbFaces = (indices.length / 3) | 0;
  38700. for (index = 0; index < nbFaces; index++) {
  38701. // get the indexes of the coordinates of each vertex of the facet
  38702. v1x = indices[index * 3] * 3;
  38703. v1y = v1x + 1;
  38704. v1z = v1x + 2;
  38705. v2x = indices[index * 3 + 1] * 3;
  38706. v2y = v2x + 1;
  38707. v2z = v2x + 2;
  38708. v3x = indices[index * 3 + 2] * 3;
  38709. v3y = v3x + 1;
  38710. v3z = v3x + 2;
  38711. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38712. p1p2y = positions[v1y] - positions[v2y];
  38713. p1p2z = positions[v1z] - positions[v2z];
  38714. p3p2x = positions[v3x] - positions[v2x];
  38715. p3p2y = positions[v3y] - positions[v2y];
  38716. p3p2z = positions[v3z] - positions[v2z];
  38717. // compute the face normal with the cross product
  38718. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38719. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38720. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38721. // normalize this normal and store it in the array facetData
  38722. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38723. length = (length === 0) ? 1.0 : length;
  38724. faceNormalx /= length;
  38725. faceNormaly /= length;
  38726. faceNormalz /= length;
  38727. if (computeFacetNormals && options) {
  38728. options.facetNormals[index].x = faceNormalx;
  38729. options.facetNormals[index].y = faceNormaly;
  38730. options.facetNormals[index].z = faceNormalz;
  38731. }
  38732. if (computeFacetPositions && options) {
  38733. // compute and the facet barycenter coordinates in the array facetPositions
  38734. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38735. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38736. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38737. }
  38738. if (computeFacetPartitioning && options) {
  38739. // store the facet indexes in arrays in the main facetPartitioning array :
  38740. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38741. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38742. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38743. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38744. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38745. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38746. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38747. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38748. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38749. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38750. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38751. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38752. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38753. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38754. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38755. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38756. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38757. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38758. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38759. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38760. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38761. // push each facet index in each block containing the vertex
  38762. options.facetPartitioning[block_idx_v1].push(index);
  38763. if (block_idx_v2 != block_idx_v1) {
  38764. options.facetPartitioning[block_idx_v2].push(index);
  38765. }
  38766. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38767. options.facetPartitioning[block_idx_v3].push(index);
  38768. }
  38769. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38770. options.facetPartitioning[block_idx_o].push(index);
  38771. }
  38772. }
  38773. if (computeDepthSort && options && options.facetPositions) {
  38774. var dsf = depthSortedFacets[index];
  38775. dsf.ind = index * 3;
  38776. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38777. }
  38778. // compute the normals anyway
  38779. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38780. normals[v1y] += faceNormaly;
  38781. normals[v1z] += faceNormalz;
  38782. normals[v2x] += faceNormalx;
  38783. normals[v2y] += faceNormaly;
  38784. normals[v2z] += faceNormalz;
  38785. normals[v3x] += faceNormalx;
  38786. normals[v3y] += faceNormaly;
  38787. normals[v3z] += faceNormalz;
  38788. }
  38789. // last normalization of each normal
  38790. for (index = 0; index < normals.length / 3; index++) {
  38791. faceNormalx = normals[index * 3];
  38792. faceNormaly = normals[index * 3 + 1];
  38793. faceNormalz = normals[index * 3 + 2];
  38794. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38795. length = (length === 0) ? 1.0 : length;
  38796. faceNormalx /= length;
  38797. faceNormaly /= length;
  38798. faceNormalz /= length;
  38799. normals[index * 3] = faceNormalx;
  38800. normals[index * 3 + 1] = faceNormaly;
  38801. normals[index * 3 + 2] = faceNormalz;
  38802. }
  38803. };
  38804. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38805. var li = indices.length;
  38806. var ln = normals.length;
  38807. var i;
  38808. var n;
  38809. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38810. switch (sideOrientation) {
  38811. case BABYLON.Mesh.FRONTSIDE:
  38812. // nothing changed
  38813. break;
  38814. case BABYLON.Mesh.BACKSIDE:
  38815. var tmp;
  38816. // indices
  38817. for (i = 0; i < li; i += 3) {
  38818. tmp = indices[i];
  38819. indices[i] = indices[i + 2];
  38820. indices[i + 2] = tmp;
  38821. }
  38822. // normals
  38823. for (n = 0; n < ln; n++) {
  38824. normals[n] = -normals[n];
  38825. }
  38826. break;
  38827. case BABYLON.Mesh.DOUBLESIDE:
  38828. // positions
  38829. var lp = positions.length;
  38830. var l = lp / 3;
  38831. for (var p = 0; p < lp; p++) {
  38832. positions[lp + p] = positions[p];
  38833. }
  38834. // indices
  38835. for (i = 0; i < li; i += 3) {
  38836. indices[i + li] = indices[i + 2] + l;
  38837. indices[i + 1 + li] = indices[i + 1] + l;
  38838. indices[i + 2 + li] = indices[i] + l;
  38839. }
  38840. // normals
  38841. for (n = 0; n < ln; n++) {
  38842. normals[ln + n] = -normals[n];
  38843. }
  38844. // uvs
  38845. var lu = uvs.length;
  38846. var u = 0;
  38847. for (u = 0; u < lu; u++) {
  38848. uvs[u + lu] = uvs[u];
  38849. }
  38850. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38851. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38852. u = 0;
  38853. for (i = 0; i < lu / 2; i++) {
  38854. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38855. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38856. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38857. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38858. u += 2;
  38859. }
  38860. break;
  38861. }
  38862. };
  38863. /**
  38864. * Applies VertexData created from the imported parameters to the geometry
  38865. * @param parsedVertexData the parsed data from an imported file
  38866. * @param geometry the geometry to apply the VertexData to
  38867. */
  38868. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38869. var vertexData = new VertexData();
  38870. // positions
  38871. var positions = parsedVertexData.positions;
  38872. if (positions) {
  38873. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38874. }
  38875. // normals
  38876. var normals = parsedVertexData.normals;
  38877. if (normals) {
  38878. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38879. }
  38880. // tangents
  38881. var tangents = parsedVertexData.tangents;
  38882. if (tangents) {
  38883. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38884. }
  38885. // uvs
  38886. var uvs = parsedVertexData.uvs;
  38887. if (uvs) {
  38888. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38889. }
  38890. // uv2s
  38891. var uv2s = parsedVertexData.uv2s;
  38892. if (uv2s) {
  38893. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38894. }
  38895. // uv3s
  38896. var uv3s = parsedVertexData.uv3s;
  38897. if (uv3s) {
  38898. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38899. }
  38900. // uv4s
  38901. var uv4s = parsedVertexData.uv4s;
  38902. if (uv4s) {
  38903. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38904. }
  38905. // uv5s
  38906. var uv5s = parsedVertexData.uv5s;
  38907. if (uv5s) {
  38908. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38909. }
  38910. // uv6s
  38911. var uv6s = parsedVertexData.uv6s;
  38912. if (uv6s) {
  38913. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38914. }
  38915. // colors
  38916. var colors = parsedVertexData.colors;
  38917. if (colors) {
  38918. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38919. }
  38920. // matricesIndices
  38921. var matricesIndices = parsedVertexData.matricesIndices;
  38922. if (matricesIndices) {
  38923. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38924. }
  38925. // matricesWeights
  38926. var matricesWeights = parsedVertexData.matricesWeights;
  38927. if (matricesWeights) {
  38928. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38929. }
  38930. // indices
  38931. var indices = parsedVertexData.indices;
  38932. if (indices) {
  38933. vertexData.indices = indices;
  38934. }
  38935. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38936. };
  38937. return VertexData;
  38938. }());
  38939. BABYLON.VertexData = VertexData;
  38940. })(BABYLON || (BABYLON = {}));
  38941. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38942. var BABYLON;
  38943. (function (BABYLON) {
  38944. /**
  38945. * Class used to store geometry data (vertex buffers + index buffer)
  38946. */
  38947. var Geometry = /** @class */ (function () {
  38948. /**
  38949. * Creates a new geometry
  38950. * @param id defines the unique ID
  38951. * @param scene defines the hosting scene
  38952. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38953. * @param updatable defines if geometry must be updatable (false by default)
  38954. * @param mesh defines the mesh that will be associated with the geometry
  38955. */
  38956. function Geometry(id, scene, vertexData, updatable, mesh) {
  38957. if (updatable === void 0) { updatable = false; }
  38958. if (mesh === void 0) { mesh = null; }
  38959. /**
  38960. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38961. */
  38962. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38963. this._totalVertices = 0;
  38964. this._isDisposed = false;
  38965. this._indexBufferIsUpdatable = false;
  38966. this.id = id;
  38967. this._engine = scene.getEngine();
  38968. this._meshes = [];
  38969. this._scene = scene;
  38970. //Init vertex buffer cache
  38971. this._vertexBuffers = {};
  38972. this._indices = [];
  38973. this._updatable = updatable;
  38974. // vertexData
  38975. if (vertexData) {
  38976. this.setAllVerticesData(vertexData, updatable);
  38977. }
  38978. else {
  38979. this._totalVertices = 0;
  38980. this._indices = [];
  38981. }
  38982. if (this._engine.getCaps().vertexArrayObject) {
  38983. this._vertexArrayObjects = {};
  38984. }
  38985. // applyToMesh
  38986. if (mesh) {
  38987. if (mesh.getClassName() === "LinesMesh") {
  38988. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38989. this._updateExtend();
  38990. }
  38991. this.applyToMesh(mesh);
  38992. mesh.computeWorldMatrix(true);
  38993. }
  38994. }
  38995. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38996. /**
  38997. * 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
  38998. */
  38999. get: function () {
  39000. return this._boundingBias;
  39001. },
  39002. /**
  39003. * 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
  39004. */
  39005. set: function (value) {
  39006. if (this._boundingBias && this._boundingBias.equals(value)) {
  39007. return;
  39008. }
  39009. this._boundingBias = value.clone();
  39010. this._updateBoundingInfo(true, null);
  39011. },
  39012. enumerable: true,
  39013. configurable: true
  39014. });
  39015. /**
  39016. * Static function used to attach a new empty geometry to a mesh
  39017. * @param mesh defines the mesh to attach the geometry to
  39018. * @returns the new {BABYLON.Geometry}
  39019. */
  39020. Geometry.CreateGeometryForMesh = function (mesh) {
  39021. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39022. geometry.applyToMesh(mesh);
  39023. return geometry;
  39024. };
  39025. Object.defineProperty(Geometry.prototype, "extend", {
  39026. /**
  39027. * Gets the current extend of the geometry
  39028. */
  39029. get: function () {
  39030. return this._extend;
  39031. },
  39032. enumerable: true,
  39033. configurable: true
  39034. });
  39035. /**
  39036. * Gets the hosting scene
  39037. * @returns the hosting {BABYLON.Scene}
  39038. */
  39039. Geometry.prototype.getScene = function () {
  39040. return this._scene;
  39041. };
  39042. /**
  39043. * Gets the hosting engine
  39044. * @returns the hosting {BABYLON.Engine}
  39045. */
  39046. Geometry.prototype.getEngine = function () {
  39047. return this._engine;
  39048. };
  39049. /**
  39050. * Defines if the geometry is ready to use
  39051. * @returns true if the geometry is ready to be used
  39052. */
  39053. Geometry.prototype.isReady = function () {
  39054. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39055. };
  39056. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39057. /**
  39058. * Gets a value indicating that the geometry should not be serialized
  39059. */
  39060. get: function () {
  39061. for (var index = 0; index < this._meshes.length; index++) {
  39062. if (!this._meshes[index].doNotSerialize) {
  39063. return false;
  39064. }
  39065. }
  39066. return true;
  39067. },
  39068. enumerable: true,
  39069. configurable: true
  39070. });
  39071. /** @hidden */
  39072. Geometry.prototype._rebuild = function () {
  39073. if (this._vertexArrayObjects) {
  39074. this._vertexArrayObjects = {};
  39075. }
  39076. // Index buffer
  39077. if (this._meshes.length !== 0 && this._indices) {
  39078. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39079. }
  39080. // Vertex buffers
  39081. for (var key in this._vertexBuffers) {
  39082. var vertexBuffer = this._vertexBuffers[key];
  39083. vertexBuffer._rebuild();
  39084. }
  39085. };
  39086. /**
  39087. * Affects all gemetry data in one call
  39088. * @param vertexData defines the geometry data
  39089. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39090. */
  39091. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39092. vertexData.applyToGeometry(this, updatable);
  39093. this.notifyUpdate();
  39094. };
  39095. /**
  39096. * Set specific vertex data
  39097. * @param kind defines the data kind (Position, normal, etc...)
  39098. * @param data defines the vertex data to use
  39099. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39100. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39101. */
  39102. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39103. if (updatable === void 0) { updatable = false; }
  39104. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39105. this.setVerticesBuffer(buffer);
  39106. };
  39107. /**
  39108. * Removes a specific vertex data
  39109. * @param kind defines the data kind (Position, normal, etc...)
  39110. */
  39111. Geometry.prototype.removeVerticesData = function (kind) {
  39112. if (this._vertexBuffers[kind]) {
  39113. this._vertexBuffers[kind].dispose();
  39114. delete this._vertexBuffers[kind];
  39115. }
  39116. };
  39117. /**
  39118. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39119. * @param buffer defines the vertex buffer to use
  39120. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39121. */
  39122. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39123. if (totalVertices === void 0) { totalVertices = null; }
  39124. var kind = buffer.getKind();
  39125. if (this._vertexBuffers[kind]) {
  39126. this._vertexBuffers[kind].dispose();
  39127. }
  39128. this._vertexBuffers[kind] = buffer;
  39129. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39130. var data = buffer.getData();
  39131. if (totalVertices != null) {
  39132. this._totalVertices = totalVertices;
  39133. }
  39134. else {
  39135. if (data != null) {
  39136. this._totalVertices = data.length / (buffer.byteStride / 4);
  39137. }
  39138. }
  39139. this._updateExtend(data);
  39140. this._resetPointsArrayCache();
  39141. var meshes = this._meshes;
  39142. var numOfMeshes = meshes.length;
  39143. for (var index = 0; index < numOfMeshes; index++) {
  39144. var mesh = meshes[index];
  39145. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39146. mesh._createGlobalSubMesh(false);
  39147. mesh.computeWorldMatrix(true);
  39148. }
  39149. }
  39150. this.notifyUpdate(kind);
  39151. if (this._vertexArrayObjects) {
  39152. this._disposeVertexArrayObjects();
  39153. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39154. }
  39155. };
  39156. /**
  39157. * Update a specific vertex buffer
  39158. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39159. * It will do nothing if the buffer is not updatable
  39160. * @param kind defines the data kind (Position, normal, etc...)
  39161. * @param data defines the data to use
  39162. * @param offset defines the offset in the target buffer where to store the data
  39163. * @param useBytes set to true if the offset is in bytes
  39164. */
  39165. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39166. if (useBytes === void 0) { useBytes = false; }
  39167. var vertexBuffer = this.getVertexBuffer(kind);
  39168. if (!vertexBuffer) {
  39169. return;
  39170. }
  39171. vertexBuffer.updateDirectly(data, offset, useBytes);
  39172. this.notifyUpdate(kind);
  39173. };
  39174. /**
  39175. * Update a specific vertex buffer
  39176. * This function will create a new buffer if the current one is not updatable
  39177. * @param kind defines the data kind (Position, normal, etc...)
  39178. * @param data defines the data to use
  39179. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39180. */
  39181. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39182. if (updateExtends === void 0) { updateExtends = false; }
  39183. var vertexBuffer = this.getVertexBuffer(kind);
  39184. if (!vertexBuffer) {
  39185. return;
  39186. }
  39187. vertexBuffer.update(data);
  39188. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39189. this._updateBoundingInfo(updateExtends, data);
  39190. }
  39191. this.notifyUpdate(kind);
  39192. };
  39193. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39194. if (updateExtends) {
  39195. this._updateExtend(data);
  39196. }
  39197. var meshes = this._meshes;
  39198. var numOfMeshes = meshes.length;
  39199. this._resetPointsArrayCache();
  39200. for (var index = 0; index < numOfMeshes; index++) {
  39201. var mesh = meshes[index];
  39202. if (updateExtends) {
  39203. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39204. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39205. var subMesh = mesh.subMeshes[subIndex];
  39206. subMesh.refreshBoundingInfo();
  39207. }
  39208. }
  39209. }
  39210. };
  39211. /** @hidden */
  39212. Geometry.prototype._bind = function (effect, indexToBind) {
  39213. if (!effect) {
  39214. return;
  39215. }
  39216. if (indexToBind === undefined) {
  39217. indexToBind = this._indexBuffer;
  39218. }
  39219. var vbs = this.getVertexBuffers();
  39220. if (!vbs) {
  39221. return;
  39222. }
  39223. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39224. this._engine.bindBuffers(vbs, indexToBind, effect);
  39225. return;
  39226. }
  39227. // Using VAO
  39228. if (!this._vertexArrayObjects[effect.key]) {
  39229. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39230. }
  39231. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39232. };
  39233. /**
  39234. * Gets total number of vertices
  39235. * @returns the total number of vertices
  39236. */
  39237. Geometry.prototype.getTotalVertices = function () {
  39238. if (!this.isReady()) {
  39239. return 0;
  39240. }
  39241. return this._totalVertices;
  39242. };
  39243. /**
  39244. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39245. * @param kind defines the data kind (Position, normal, etc...)
  39246. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39247. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39248. * @returns a float array containing vertex data
  39249. */
  39250. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39251. var vertexBuffer = this.getVertexBuffer(kind);
  39252. if (!vertexBuffer) {
  39253. return null;
  39254. }
  39255. var data = vertexBuffer.getData();
  39256. if (!data) {
  39257. return null;
  39258. }
  39259. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39260. var count = this._totalVertices * vertexBuffer.getSize();
  39261. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39262. var copy_1 = new Array(count);
  39263. vertexBuffer.forEach(count, function (value, index) {
  39264. copy_1[index] = value;
  39265. });
  39266. return copy_1;
  39267. }
  39268. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39269. if (data instanceof Array) {
  39270. var offset = vertexBuffer.byteOffset / 4;
  39271. return BABYLON.Tools.Slice(data, offset, offset + count);
  39272. }
  39273. else if (data instanceof ArrayBuffer) {
  39274. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39275. }
  39276. else {
  39277. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39278. }
  39279. }
  39280. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39281. return BABYLON.Tools.Slice(data);
  39282. }
  39283. return data;
  39284. };
  39285. /**
  39286. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39287. * @param kind defines the data kind (Position, normal, etc...)
  39288. * @returns true if the vertex buffer with the specified kind is updatable
  39289. */
  39290. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39291. var vb = this._vertexBuffers[kind];
  39292. if (!vb) {
  39293. return false;
  39294. }
  39295. return vb.isUpdatable();
  39296. };
  39297. /**
  39298. * Gets a specific vertex buffer
  39299. * @param kind defines the data kind (Position, normal, etc...)
  39300. * @returns a {BABYLON.VertexBuffer}
  39301. */
  39302. Geometry.prototype.getVertexBuffer = function (kind) {
  39303. if (!this.isReady()) {
  39304. return null;
  39305. }
  39306. return this._vertexBuffers[kind];
  39307. };
  39308. /**
  39309. * Returns all vertex buffers
  39310. * @return an object holding all vertex buffers indexed by kind
  39311. */
  39312. Geometry.prototype.getVertexBuffers = function () {
  39313. if (!this.isReady()) {
  39314. return null;
  39315. }
  39316. return this._vertexBuffers;
  39317. };
  39318. /**
  39319. * Gets a boolean indicating if specific vertex buffer is present
  39320. * @param kind defines the data kind (Position, normal, etc...)
  39321. * @returns true if data is present
  39322. */
  39323. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39324. if (!this._vertexBuffers) {
  39325. if (this._delayInfo) {
  39326. return this._delayInfo.indexOf(kind) !== -1;
  39327. }
  39328. return false;
  39329. }
  39330. return this._vertexBuffers[kind] !== undefined;
  39331. };
  39332. /**
  39333. * Gets a list of all attached data kinds (Position, normal, etc...)
  39334. * @returns a list of string containing all kinds
  39335. */
  39336. Geometry.prototype.getVerticesDataKinds = function () {
  39337. var result = [];
  39338. var kind;
  39339. if (!this._vertexBuffers && this._delayInfo) {
  39340. for (kind in this._delayInfo) {
  39341. result.push(kind);
  39342. }
  39343. }
  39344. else {
  39345. for (kind in this._vertexBuffers) {
  39346. result.push(kind);
  39347. }
  39348. }
  39349. return result;
  39350. };
  39351. /**
  39352. * Update index buffer
  39353. * @param indices defines the indices to store in the index buffer
  39354. * @param offset defines the offset in the target buffer where to store the data
  39355. */
  39356. Geometry.prototype.updateIndices = function (indices, offset) {
  39357. if (!this._indexBuffer) {
  39358. return;
  39359. }
  39360. if (!this._indexBufferIsUpdatable) {
  39361. this.setIndices(indices, null, true);
  39362. }
  39363. else {
  39364. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39365. }
  39366. };
  39367. /**
  39368. * Creates a new index buffer
  39369. * @param indices defines the indices to store in the index buffer
  39370. * @param totalVertices defines the total number of vertices (could be null)
  39371. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39372. */
  39373. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39374. if (totalVertices === void 0) { totalVertices = null; }
  39375. if (updatable === void 0) { updatable = false; }
  39376. if (this._indexBuffer) {
  39377. this._engine._releaseBuffer(this._indexBuffer);
  39378. }
  39379. this._disposeVertexArrayObjects();
  39380. this._indices = indices;
  39381. this._indexBufferIsUpdatable = updatable;
  39382. if (this._meshes.length !== 0 && this._indices) {
  39383. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39384. }
  39385. if (totalVertices != undefined) { // including null and undefined
  39386. this._totalVertices = totalVertices;
  39387. }
  39388. var meshes = this._meshes;
  39389. var numOfMeshes = meshes.length;
  39390. for (var index = 0; index < numOfMeshes; index++) {
  39391. meshes[index]._createGlobalSubMesh(true);
  39392. }
  39393. this.notifyUpdate();
  39394. };
  39395. /**
  39396. * Return the total number of indices
  39397. * @returns the total number of indices
  39398. */
  39399. Geometry.prototype.getTotalIndices = function () {
  39400. if (!this.isReady()) {
  39401. return 0;
  39402. }
  39403. return this._indices.length;
  39404. };
  39405. /**
  39406. * Gets the index buffer array
  39407. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39408. * @returns the index buffer array
  39409. */
  39410. Geometry.prototype.getIndices = function (copyWhenShared) {
  39411. if (!this.isReady()) {
  39412. return null;
  39413. }
  39414. var orig = this._indices;
  39415. if (!copyWhenShared || this._meshes.length === 1) {
  39416. return orig;
  39417. }
  39418. else {
  39419. var len = orig.length;
  39420. var copy = [];
  39421. for (var i = 0; i < len; i++) {
  39422. copy.push(orig[i]);
  39423. }
  39424. return copy;
  39425. }
  39426. };
  39427. /**
  39428. * Gets the index buffer
  39429. * @return the index buffer
  39430. */
  39431. Geometry.prototype.getIndexBuffer = function () {
  39432. if (!this.isReady()) {
  39433. return null;
  39434. }
  39435. return this._indexBuffer;
  39436. };
  39437. /** @hidden */
  39438. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39439. if (effect === void 0) { effect = null; }
  39440. if (!effect || !this._vertexArrayObjects) {
  39441. return;
  39442. }
  39443. if (this._vertexArrayObjects[effect.key]) {
  39444. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39445. delete this._vertexArrayObjects[effect.key];
  39446. }
  39447. };
  39448. /**
  39449. * Release the associated resources for a specific mesh
  39450. * @param mesh defines the source mesh
  39451. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39452. */
  39453. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39454. var meshes = this._meshes;
  39455. var index = meshes.indexOf(mesh);
  39456. if (index === -1) {
  39457. return;
  39458. }
  39459. meshes.splice(index, 1);
  39460. mesh._geometry = null;
  39461. if (meshes.length === 0 && shouldDispose) {
  39462. this.dispose();
  39463. }
  39464. };
  39465. /**
  39466. * Apply current geometry to a given mesh
  39467. * @param mesh defines the mesh to apply geometry to
  39468. */
  39469. Geometry.prototype.applyToMesh = function (mesh) {
  39470. if (mesh._geometry === this) {
  39471. return;
  39472. }
  39473. var previousGeometry = mesh._geometry;
  39474. if (previousGeometry) {
  39475. previousGeometry.releaseForMesh(mesh);
  39476. }
  39477. var meshes = this._meshes;
  39478. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39479. mesh._geometry = this;
  39480. this._scene.pushGeometry(this);
  39481. meshes.push(mesh);
  39482. if (this.isReady()) {
  39483. this._applyToMesh(mesh);
  39484. }
  39485. else {
  39486. mesh._boundingInfo = this._boundingInfo;
  39487. }
  39488. };
  39489. Geometry.prototype._updateExtend = function (data) {
  39490. if (data === void 0) { data = null; }
  39491. if (!data) {
  39492. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39493. }
  39494. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39495. };
  39496. Geometry.prototype._applyToMesh = function (mesh) {
  39497. var numOfMeshes = this._meshes.length;
  39498. // vertexBuffers
  39499. for (var kind in this._vertexBuffers) {
  39500. if (numOfMeshes === 1) {
  39501. this._vertexBuffers[kind].create();
  39502. }
  39503. var buffer = this._vertexBuffers[kind].getBuffer();
  39504. if (buffer)
  39505. buffer.references = numOfMeshes;
  39506. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39507. if (!this._extend) {
  39508. this._updateExtend();
  39509. }
  39510. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39511. mesh._createGlobalSubMesh(false);
  39512. //bounding info was just created again, world matrix should be applied again.
  39513. mesh._updateBoundingInfo();
  39514. }
  39515. }
  39516. // indexBuffer
  39517. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39518. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39519. }
  39520. if (this._indexBuffer) {
  39521. this._indexBuffer.references = numOfMeshes;
  39522. }
  39523. };
  39524. Geometry.prototype.notifyUpdate = function (kind) {
  39525. if (this.onGeometryUpdated) {
  39526. this.onGeometryUpdated(this, kind);
  39527. }
  39528. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39529. var mesh = _a[_i];
  39530. mesh._markSubMeshesAsAttributesDirty();
  39531. }
  39532. };
  39533. /**
  39534. * Load the geometry if it was flagged as delay loaded
  39535. * @param scene defines the hosting scene
  39536. * @param onLoaded defines a callback called when the geometry is loaded
  39537. */
  39538. Geometry.prototype.load = function (scene, onLoaded) {
  39539. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39540. return;
  39541. }
  39542. if (this.isReady()) {
  39543. if (onLoaded) {
  39544. onLoaded();
  39545. }
  39546. return;
  39547. }
  39548. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39549. this._queueLoad(scene, onLoaded);
  39550. };
  39551. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39552. var _this = this;
  39553. if (!this.delayLoadingFile) {
  39554. return;
  39555. }
  39556. scene._addPendingData(this);
  39557. scene._loadFile(this.delayLoadingFile, function (data) {
  39558. if (!_this._delayLoadingFunction) {
  39559. return;
  39560. }
  39561. _this._delayLoadingFunction(JSON.parse(data), _this);
  39562. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39563. _this._delayInfo = [];
  39564. scene._removePendingData(_this);
  39565. var meshes = _this._meshes;
  39566. var numOfMeshes = meshes.length;
  39567. for (var index = 0; index < numOfMeshes; index++) {
  39568. _this._applyToMesh(meshes[index]);
  39569. }
  39570. if (onLoaded) {
  39571. onLoaded();
  39572. }
  39573. }, undefined, true);
  39574. };
  39575. /**
  39576. * Invert the geometry to move from a right handed system to a left handed one.
  39577. */
  39578. Geometry.prototype.toLeftHanded = function () {
  39579. // Flip faces
  39580. var tIndices = this.getIndices(false);
  39581. if (tIndices != null && tIndices.length > 0) {
  39582. for (var i = 0; i < tIndices.length; i += 3) {
  39583. var tTemp = tIndices[i + 0];
  39584. tIndices[i + 0] = tIndices[i + 2];
  39585. tIndices[i + 2] = tTemp;
  39586. }
  39587. this.setIndices(tIndices);
  39588. }
  39589. // Negate position.z
  39590. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39591. if (tPositions != null && tPositions.length > 0) {
  39592. for (var i = 0; i < tPositions.length; i += 3) {
  39593. tPositions[i + 2] = -tPositions[i + 2];
  39594. }
  39595. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39596. }
  39597. // Negate normal.z
  39598. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39599. if (tNormals != null && tNormals.length > 0) {
  39600. for (var i = 0; i < tNormals.length; i += 3) {
  39601. tNormals[i + 2] = -tNormals[i + 2];
  39602. }
  39603. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39604. }
  39605. };
  39606. // Cache
  39607. /** @hidden */
  39608. Geometry.prototype._resetPointsArrayCache = function () {
  39609. this._positions = null;
  39610. };
  39611. /** @hidden */
  39612. Geometry.prototype._generatePointsArray = function () {
  39613. if (this._positions)
  39614. return true;
  39615. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39616. if (!data || data.length === 0) {
  39617. return false;
  39618. }
  39619. this._positions = [];
  39620. for (var index = 0; index < data.length; index += 3) {
  39621. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39622. }
  39623. return true;
  39624. };
  39625. /**
  39626. * Gets a value indicating if the geometry is disposed
  39627. * @returns true if the geometry was disposed
  39628. */
  39629. Geometry.prototype.isDisposed = function () {
  39630. return this._isDisposed;
  39631. };
  39632. Geometry.prototype._disposeVertexArrayObjects = function () {
  39633. if (this._vertexArrayObjects) {
  39634. for (var kind in this._vertexArrayObjects) {
  39635. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39636. }
  39637. this._vertexArrayObjects = {};
  39638. }
  39639. };
  39640. /**
  39641. * Free all associated resources
  39642. */
  39643. Geometry.prototype.dispose = function () {
  39644. var meshes = this._meshes;
  39645. var numOfMeshes = meshes.length;
  39646. var index;
  39647. for (index = 0; index < numOfMeshes; index++) {
  39648. this.releaseForMesh(meshes[index]);
  39649. }
  39650. this._meshes = [];
  39651. this._disposeVertexArrayObjects();
  39652. for (var kind in this._vertexBuffers) {
  39653. this._vertexBuffers[kind].dispose();
  39654. }
  39655. this._vertexBuffers = {};
  39656. this._totalVertices = 0;
  39657. if (this._indexBuffer) {
  39658. this._engine._releaseBuffer(this._indexBuffer);
  39659. }
  39660. this._indexBuffer = null;
  39661. this._indices = [];
  39662. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39663. this.delayLoadingFile = null;
  39664. this._delayLoadingFunction = null;
  39665. this._delayInfo = [];
  39666. this._boundingInfo = null;
  39667. this._scene.removeGeometry(this);
  39668. this._isDisposed = true;
  39669. };
  39670. /**
  39671. * Clone the current geometry into a new geometry
  39672. * @param id defines the unique ID of the new geometry
  39673. * @returns a new geometry object
  39674. */
  39675. Geometry.prototype.copy = function (id) {
  39676. var vertexData = new BABYLON.VertexData();
  39677. vertexData.indices = [];
  39678. var indices = this.getIndices();
  39679. if (indices) {
  39680. for (var index = 0; index < indices.length; index++) {
  39681. vertexData.indices.push(indices[index]);
  39682. }
  39683. }
  39684. var updatable = false;
  39685. var stopChecking = false;
  39686. var kind;
  39687. for (kind in this._vertexBuffers) {
  39688. // using slice() to make a copy of the array and not just reference it
  39689. var data = this.getVerticesData(kind);
  39690. if (data instanceof Float32Array) {
  39691. vertexData.set(new Float32Array(data), kind);
  39692. }
  39693. else {
  39694. vertexData.set(data.slice(0), kind);
  39695. }
  39696. if (!stopChecking) {
  39697. var vb = this.getVertexBuffer(kind);
  39698. if (vb) {
  39699. updatable = vb.isUpdatable();
  39700. stopChecking = !updatable;
  39701. }
  39702. }
  39703. }
  39704. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39705. geometry.delayLoadState = this.delayLoadState;
  39706. geometry.delayLoadingFile = this.delayLoadingFile;
  39707. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39708. for (kind in this._delayInfo) {
  39709. geometry._delayInfo = geometry._delayInfo || [];
  39710. geometry._delayInfo.push(kind);
  39711. }
  39712. // Bounding info
  39713. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39714. return geometry;
  39715. };
  39716. /**
  39717. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39718. * @return a JSON representation of the current geometry data (without the vertices data)
  39719. */
  39720. Geometry.prototype.serialize = function () {
  39721. var serializationObject = {};
  39722. serializationObject.id = this.id;
  39723. serializationObject.updatable = this._updatable;
  39724. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39725. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39726. }
  39727. return serializationObject;
  39728. };
  39729. Geometry.prototype.toNumberArray = function (origin) {
  39730. if (Array.isArray(origin)) {
  39731. return origin;
  39732. }
  39733. else {
  39734. return Array.prototype.slice.call(origin);
  39735. }
  39736. };
  39737. /**
  39738. * Serialize all vertices data into a JSON oject
  39739. * @returns a JSON representation of the current geometry data
  39740. */
  39741. Geometry.prototype.serializeVerticeData = function () {
  39742. var serializationObject = this.serialize();
  39743. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39744. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39745. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39746. serializationObject.positions._updatable = true;
  39747. }
  39748. }
  39749. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39750. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39751. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39752. serializationObject.normals._updatable = true;
  39753. }
  39754. }
  39755. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39756. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39757. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39758. serializationObject.tangets._updatable = true;
  39759. }
  39760. }
  39761. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39762. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39763. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39764. serializationObject.uvs._updatable = true;
  39765. }
  39766. }
  39767. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39768. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39769. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39770. serializationObject.uv2s._updatable = true;
  39771. }
  39772. }
  39773. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39774. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39775. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39776. serializationObject.uv3s._updatable = true;
  39777. }
  39778. }
  39779. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39780. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39781. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39782. serializationObject.uv4s._updatable = true;
  39783. }
  39784. }
  39785. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39786. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39787. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39788. serializationObject.uv5s._updatable = true;
  39789. }
  39790. }
  39791. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39792. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39793. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39794. serializationObject.uv6s._updatable = true;
  39795. }
  39796. }
  39797. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39798. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39799. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39800. serializationObject.colors._updatable = true;
  39801. }
  39802. }
  39803. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39804. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39805. serializationObject.matricesIndices._isExpanded = true;
  39806. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39807. serializationObject.matricesIndices._updatable = true;
  39808. }
  39809. }
  39810. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39811. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39812. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39813. serializationObject.matricesWeights._updatable = true;
  39814. }
  39815. }
  39816. serializationObject.indices = this.toNumberArray(this.getIndices());
  39817. return serializationObject;
  39818. };
  39819. // Statics
  39820. /**
  39821. * Extracts a clone of a mesh geometry
  39822. * @param mesh defines the source mesh
  39823. * @param id defines the unique ID of the new geometry object
  39824. * @returns the new geometry object
  39825. */
  39826. Geometry.ExtractFromMesh = function (mesh, id) {
  39827. var geometry = mesh._geometry;
  39828. if (!geometry) {
  39829. return null;
  39830. }
  39831. return geometry.copy(id);
  39832. };
  39833. /**
  39834. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39835. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39836. * Be aware Math.random() could cause collisions, but:
  39837. * "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"
  39838. * @returns a string containing a new GUID
  39839. */
  39840. Geometry.RandomId = function () {
  39841. return BABYLON.Tools.RandomId();
  39842. };
  39843. /** @hidden */
  39844. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39845. var scene = mesh.getScene();
  39846. // Geometry
  39847. var geometryId = parsedGeometry.geometryId;
  39848. if (geometryId) {
  39849. var geometry = scene.getGeometryByID(geometryId);
  39850. if (geometry) {
  39851. geometry.applyToMesh(mesh);
  39852. }
  39853. }
  39854. else if (parsedGeometry instanceof ArrayBuffer) {
  39855. var binaryInfo = mesh._binaryInfo;
  39856. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39857. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39858. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39859. }
  39860. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39861. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39862. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39863. }
  39864. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39865. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39866. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39867. }
  39868. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39869. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39870. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39871. }
  39872. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39873. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39874. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39875. }
  39876. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39877. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39878. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39879. }
  39880. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39881. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39882. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39883. }
  39884. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39885. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39886. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39887. }
  39888. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39889. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39890. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39891. }
  39892. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39893. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39894. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39895. }
  39896. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39897. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39898. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39899. }
  39900. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39901. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39902. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39903. }
  39904. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39905. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39906. mesh.setIndices(indicesData, null);
  39907. }
  39908. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39909. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39910. mesh.subMeshes = [];
  39911. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39912. var materialIndex = subMeshesData[(i * 5) + 0];
  39913. var verticesStart = subMeshesData[(i * 5) + 1];
  39914. var verticesCount = subMeshesData[(i * 5) + 2];
  39915. var indexStart = subMeshesData[(i * 5) + 3];
  39916. var indexCount = subMeshesData[(i * 5) + 4];
  39917. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39918. }
  39919. }
  39920. }
  39921. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39922. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39924. if (parsedGeometry.tangents) {
  39925. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39926. }
  39927. if (parsedGeometry.uvs) {
  39928. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39929. }
  39930. if (parsedGeometry.uvs2) {
  39931. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39932. }
  39933. if (parsedGeometry.uvs3) {
  39934. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39935. }
  39936. if (parsedGeometry.uvs4) {
  39937. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39938. }
  39939. if (parsedGeometry.uvs5) {
  39940. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39941. }
  39942. if (parsedGeometry.uvs6) {
  39943. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39944. }
  39945. if (parsedGeometry.colors) {
  39946. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39947. }
  39948. if (parsedGeometry.matricesIndices) {
  39949. if (!parsedGeometry.matricesIndices._isExpanded) {
  39950. var floatIndices = [];
  39951. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39952. var matricesIndex = parsedGeometry.matricesIndices[i];
  39953. floatIndices.push(matricesIndex & 0x000000FF);
  39954. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39955. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39956. floatIndices.push(matricesIndex >> 24);
  39957. }
  39958. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39959. }
  39960. else {
  39961. delete parsedGeometry.matricesIndices._isExpanded;
  39962. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39963. }
  39964. }
  39965. if (parsedGeometry.matricesIndicesExtra) {
  39966. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39967. var floatIndices = [];
  39968. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39969. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39970. floatIndices.push(matricesIndex & 0x000000FF);
  39971. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39972. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39973. floatIndices.push(matricesIndex >> 24);
  39974. }
  39975. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39976. }
  39977. else {
  39978. delete parsedGeometry.matricesIndices._isExpanded;
  39979. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39980. }
  39981. }
  39982. if (parsedGeometry.matricesWeights) {
  39983. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39984. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39985. }
  39986. if (parsedGeometry.matricesWeightsExtra) {
  39987. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39988. }
  39989. mesh.setIndices(parsedGeometry.indices, null);
  39990. }
  39991. // SubMeshes
  39992. if (parsedGeometry.subMeshes) {
  39993. mesh.subMeshes = [];
  39994. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39995. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39996. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39997. }
  39998. }
  39999. // Flat shading
  40000. if (mesh._shouldGenerateFlatShading) {
  40001. mesh.convertToFlatShadedMesh();
  40002. delete mesh._shouldGenerateFlatShading;
  40003. }
  40004. // Update
  40005. mesh.computeWorldMatrix(true);
  40006. // Octree
  40007. var sceneOctree = scene.selectionOctree;
  40008. if (sceneOctree !== undefined && sceneOctree !== null) {
  40009. sceneOctree.addMesh(mesh);
  40010. }
  40011. };
  40012. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40013. var epsilon = 1e-3;
  40014. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40015. return;
  40016. }
  40017. var noInfluenceBoneIndex = 0.0;
  40018. if (parsedGeometry.skeletonId > -1) {
  40019. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40020. if (!skeleton) {
  40021. return;
  40022. }
  40023. noInfluenceBoneIndex = skeleton.bones.length;
  40024. }
  40025. else {
  40026. return;
  40027. }
  40028. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40029. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40030. var matricesWeights = parsedGeometry.matricesWeights;
  40031. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40032. var influencers = parsedGeometry.numBoneInfluencer;
  40033. var size = matricesWeights.length;
  40034. for (var i = 0; i < size; i += 4) {
  40035. var weight = 0.0;
  40036. var firstZeroWeight = -1;
  40037. for (var j = 0; j < 4; j++) {
  40038. var w = matricesWeights[i + j];
  40039. weight += w;
  40040. if (w < epsilon && firstZeroWeight < 0) {
  40041. firstZeroWeight = j;
  40042. }
  40043. }
  40044. if (matricesWeightsExtra) {
  40045. for (var j = 0; j < 4; j++) {
  40046. var w = matricesWeightsExtra[i + j];
  40047. weight += w;
  40048. if (w < epsilon && firstZeroWeight < 0) {
  40049. firstZeroWeight = j + 4;
  40050. }
  40051. }
  40052. }
  40053. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40054. firstZeroWeight = influencers - 1;
  40055. }
  40056. if (weight > epsilon) {
  40057. var mweight = 1.0 / weight;
  40058. for (var j = 0; j < 4; j++) {
  40059. matricesWeights[i + j] *= mweight;
  40060. }
  40061. if (matricesWeightsExtra) {
  40062. for (var j = 0; j < 4; j++) {
  40063. matricesWeightsExtra[i + j] *= mweight;
  40064. }
  40065. }
  40066. }
  40067. else {
  40068. if (firstZeroWeight >= 4) {
  40069. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40070. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40071. }
  40072. else {
  40073. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40074. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40075. }
  40076. }
  40077. }
  40078. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40079. if (parsedGeometry.matricesWeightsExtra) {
  40080. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40081. }
  40082. };
  40083. /**
  40084. * Create a new geometry from persisted data (Using .babylon file format)
  40085. * @param parsedVertexData defines the persisted data
  40086. * @param scene defines the hosting scene
  40087. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40088. * @returns the new geometry object
  40089. */
  40090. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40091. if (scene.getGeometryByID(parsedVertexData.id)) {
  40092. return null; // null since geometry could be something else than a box...
  40093. }
  40094. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40095. if (BABYLON.Tags) {
  40096. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40097. }
  40098. if (parsedVertexData.delayLoadingFile) {
  40099. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40100. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40101. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40102. geometry._delayInfo = [];
  40103. if (parsedVertexData.hasUVs) {
  40104. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40105. }
  40106. if (parsedVertexData.hasUVs2) {
  40107. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40108. }
  40109. if (parsedVertexData.hasUVs3) {
  40110. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40111. }
  40112. if (parsedVertexData.hasUVs4) {
  40113. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40114. }
  40115. if (parsedVertexData.hasUVs5) {
  40116. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40117. }
  40118. if (parsedVertexData.hasUVs6) {
  40119. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40120. }
  40121. if (parsedVertexData.hasColors) {
  40122. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40123. }
  40124. if (parsedVertexData.hasMatricesIndices) {
  40125. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40126. }
  40127. if (parsedVertexData.hasMatricesWeights) {
  40128. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40129. }
  40130. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40131. }
  40132. else {
  40133. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40134. }
  40135. scene.pushGeometry(geometry, true);
  40136. return geometry;
  40137. };
  40138. return Geometry;
  40139. }());
  40140. BABYLON.Geometry = Geometry;
  40141. // Primitives
  40142. /// Abstract class
  40143. /**
  40144. * Abstract class used to provide common services for all typed geometries
  40145. * @hidden
  40146. */
  40147. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40148. __extends(_PrimitiveGeometry, _super);
  40149. /**
  40150. * Creates a new typed geometry
  40151. * @param id defines the unique ID of the geometry
  40152. * @param scene defines the hosting scene
  40153. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40154. * @param mesh defines the hosting mesh (can be null)
  40155. */
  40156. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40157. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40158. if (mesh === void 0) { mesh = null; }
  40159. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40160. _this._canBeRegenerated = _canBeRegenerated;
  40161. _this._beingRegenerated = true;
  40162. _this.regenerate();
  40163. _this._beingRegenerated = false;
  40164. return _this;
  40165. }
  40166. /**
  40167. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40168. * @returns true if the geometry can be regenerated
  40169. */
  40170. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40171. return this._canBeRegenerated;
  40172. };
  40173. /**
  40174. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40175. */
  40176. _PrimitiveGeometry.prototype.regenerate = function () {
  40177. if (!this._canBeRegenerated) {
  40178. return;
  40179. }
  40180. this._beingRegenerated = true;
  40181. this.setAllVerticesData(this._regenerateVertexData(), false);
  40182. this._beingRegenerated = false;
  40183. };
  40184. /**
  40185. * Clone the geometry
  40186. * @param id defines the unique ID of the new geometry
  40187. * @returns the new geometry
  40188. */
  40189. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40190. return _super.prototype.copy.call(this, id);
  40191. };
  40192. // overrides
  40193. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40194. if (!this._beingRegenerated) {
  40195. return;
  40196. }
  40197. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40198. };
  40199. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40200. if (!this._beingRegenerated) {
  40201. return;
  40202. }
  40203. _super.prototype.setVerticesData.call(this, kind, data, false);
  40204. };
  40205. // to override
  40206. /** @hidden */
  40207. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40208. throw new Error("Abstract method");
  40209. };
  40210. _PrimitiveGeometry.prototype.copy = function (id) {
  40211. throw new Error("Must be overriden in sub-classes.");
  40212. };
  40213. _PrimitiveGeometry.prototype.serialize = function () {
  40214. var serializationObject = _super.prototype.serialize.call(this);
  40215. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40216. return serializationObject;
  40217. };
  40218. return _PrimitiveGeometry;
  40219. }(Geometry));
  40220. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40221. /**
  40222. * Creates a ribbon geometry
  40223. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40224. */
  40225. var RibbonGeometry = /** @class */ (function (_super) {
  40226. __extends(RibbonGeometry, _super);
  40227. /**
  40228. * Creates a ribbon geometry
  40229. * @param id defines the unique ID of the geometry
  40230. * @param scene defines the hosting scene
  40231. * @param pathArray defines the array of paths to use
  40232. * @param closeArray defines if the last path and the first path must be joined
  40233. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40234. * @param offset defines the offset between points
  40235. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40236. * @param mesh defines the hosting mesh (can be null)
  40237. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40238. */
  40239. function RibbonGeometry(id, scene,
  40240. /**
  40241. * Defines the array of paths to use
  40242. */
  40243. pathArray,
  40244. /**
  40245. * Defines if the last and first points of each path in your pathArray must be joined
  40246. */
  40247. closeArray,
  40248. /**
  40249. * Defines if the last and first points of each path in your pathArray must be joined
  40250. */
  40251. closePath,
  40252. /**
  40253. * Defines the offset between points
  40254. */
  40255. offset, canBeRegenerated, mesh,
  40256. /**
  40257. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40258. */
  40259. side) {
  40260. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40261. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40262. _this.pathArray = pathArray;
  40263. _this.closeArray = closeArray;
  40264. _this.closePath = closePath;
  40265. _this.offset = offset;
  40266. _this.side = side;
  40267. return _this;
  40268. }
  40269. /** @hidden */
  40270. RibbonGeometry.prototype._regenerateVertexData = function () {
  40271. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40272. };
  40273. RibbonGeometry.prototype.copy = function (id) {
  40274. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40275. };
  40276. return RibbonGeometry;
  40277. }(_PrimitiveGeometry));
  40278. BABYLON.RibbonGeometry = RibbonGeometry;
  40279. /**
  40280. * Creates a box geometry
  40281. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40282. */
  40283. var BoxGeometry = /** @class */ (function (_super) {
  40284. __extends(BoxGeometry, _super);
  40285. /**
  40286. * Creates a box geometry
  40287. * @param id defines the unique ID of the geometry
  40288. * @param scene defines the hosting scene
  40289. * @param size defines the zise of the box (width, height and depth are the same)
  40290. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40291. * @param mesh defines the hosting mesh (can be null)
  40292. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40293. */
  40294. function BoxGeometry(id, scene,
  40295. /**
  40296. * Defines the zise of the box (width, height and depth are the same)
  40297. */
  40298. size, canBeRegenerated, mesh,
  40299. /**
  40300. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40301. */
  40302. side) {
  40303. if (mesh === void 0) { mesh = null; }
  40304. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40305. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40306. _this.size = size;
  40307. _this.side = side;
  40308. return _this;
  40309. }
  40310. BoxGeometry.prototype._regenerateVertexData = function () {
  40311. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40312. };
  40313. BoxGeometry.prototype.copy = function (id) {
  40314. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40315. };
  40316. BoxGeometry.prototype.serialize = function () {
  40317. var serializationObject = _super.prototype.serialize.call(this);
  40318. serializationObject.size = this.size;
  40319. return serializationObject;
  40320. };
  40321. BoxGeometry.Parse = function (parsedBox, scene) {
  40322. if (scene.getGeometryByID(parsedBox.id)) {
  40323. return null; // null since geometry could be something else than a box...
  40324. }
  40325. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40326. if (BABYLON.Tags) {
  40327. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40328. }
  40329. scene.pushGeometry(box, true);
  40330. return box;
  40331. };
  40332. return BoxGeometry;
  40333. }(_PrimitiveGeometry));
  40334. BABYLON.BoxGeometry = BoxGeometry;
  40335. /**
  40336. * Creates a sphere geometry
  40337. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40338. */
  40339. var SphereGeometry = /** @class */ (function (_super) {
  40340. __extends(SphereGeometry, _super);
  40341. /**
  40342. * Create a new sphere geometry
  40343. * @param id defines the unique ID of the geometry
  40344. * @param scene defines the hosting scene
  40345. * @param segments defines the number of segments to use to create the sphere
  40346. * @param diameter defines the diameter of the sphere
  40347. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40348. * @param mesh defines the hosting mesh (can be null)
  40349. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40350. */
  40351. function SphereGeometry(id, scene,
  40352. /**
  40353. * Defines the number of segments to use to create the sphere
  40354. */
  40355. segments,
  40356. /**
  40357. * Defines the diameter of the sphere
  40358. */
  40359. diameter, canBeRegenerated, mesh,
  40360. /**
  40361. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40362. */
  40363. side) {
  40364. if (mesh === void 0) { mesh = null; }
  40365. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40366. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40367. _this.segments = segments;
  40368. _this.diameter = diameter;
  40369. _this.side = side;
  40370. return _this;
  40371. }
  40372. SphereGeometry.prototype._regenerateVertexData = function () {
  40373. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40374. };
  40375. SphereGeometry.prototype.copy = function (id) {
  40376. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40377. };
  40378. SphereGeometry.prototype.serialize = function () {
  40379. var serializationObject = _super.prototype.serialize.call(this);
  40380. serializationObject.segments = this.segments;
  40381. serializationObject.diameter = this.diameter;
  40382. return serializationObject;
  40383. };
  40384. SphereGeometry.Parse = function (parsedSphere, scene) {
  40385. if (scene.getGeometryByID(parsedSphere.id)) {
  40386. return null; // null since geometry could be something else than a sphere...
  40387. }
  40388. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40389. if (BABYLON.Tags) {
  40390. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40391. }
  40392. scene.pushGeometry(sphere, true);
  40393. return sphere;
  40394. };
  40395. return SphereGeometry;
  40396. }(_PrimitiveGeometry));
  40397. BABYLON.SphereGeometry = SphereGeometry;
  40398. /**
  40399. * Creates a disc geometry
  40400. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40401. */
  40402. var DiscGeometry = /** @class */ (function (_super) {
  40403. __extends(DiscGeometry, _super);
  40404. /**
  40405. * Creates a new disc geometry
  40406. * @param id defines the unique ID of the geometry
  40407. * @param scene defines the hosting scene
  40408. * @param radius defines the radius of the disc
  40409. * @param tessellation defines the tesselation factor to apply to the disc
  40410. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40411. * @param mesh defines the hosting mesh (can be null)
  40412. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40413. */
  40414. function DiscGeometry(id, scene,
  40415. /**
  40416. * Defines the radius of the disc
  40417. */
  40418. radius,
  40419. /**
  40420. * Defines the tesselation factor to apply to the disc
  40421. */
  40422. tessellation, canBeRegenerated, mesh,
  40423. /**
  40424. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40425. */
  40426. side) {
  40427. if (mesh === void 0) { mesh = null; }
  40428. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40429. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40430. _this.radius = radius;
  40431. _this.tessellation = tessellation;
  40432. _this.side = side;
  40433. return _this;
  40434. }
  40435. DiscGeometry.prototype._regenerateVertexData = function () {
  40436. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40437. };
  40438. DiscGeometry.prototype.copy = function (id) {
  40439. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40440. };
  40441. return DiscGeometry;
  40442. }(_PrimitiveGeometry));
  40443. BABYLON.DiscGeometry = DiscGeometry;
  40444. /**
  40445. * Creates a new cylinder geometry
  40446. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40447. */
  40448. var CylinderGeometry = /** @class */ (function (_super) {
  40449. __extends(CylinderGeometry, _super);
  40450. /**
  40451. * Creates a new cylinder geometry
  40452. * @param id defines the unique ID of the geometry
  40453. * @param scene defines the hosting scene
  40454. * @param height defines the height of the cylinder
  40455. * @param diameterTop defines the diameter of the cylinder's top cap
  40456. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40457. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40458. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40459. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40460. * @param mesh defines the hosting mesh (can be null)
  40461. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40462. */
  40463. function CylinderGeometry(id, scene,
  40464. /**
  40465. * Defines the height of the cylinder
  40466. */
  40467. height,
  40468. /**
  40469. * Defines the diameter of the cylinder's top cap
  40470. */
  40471. diameterTop,
  40472. /**
  40473. * Defines the diameter of the cylinder's bottom cap
  40474. */
  40475. diameterBottom,
  40476. /**
  40477. * Defines the tessellation factor to apply to the cylinder
  40478. */
  40479. tessellation,
  40480. /**
  40481. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40482. */
  40483. subdivisions, canBeRegenerated, mesh,
  40484. /**
  40485. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40486. */
  40487. side) {
  40488. if (subdivisions === void 0) { subdivisions = 1; }
  40489. if (mesh === void 0) { mesh = null; }
  40490. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40491. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40492. _this.height = height;
  40493. _this.diameterTop = diameterTop;
  40494. _this.diameterBottom = diameterBottom;
  40495. _this.tessellation = tessellation;
  40496. _this.subdivisions = subdivisions;
  40497. _this.side = side;
  40498. return _this;
  40499. }
  40500. CylinderGeometry.prototype._regenerateVertexData = function () {
  40501. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40502. };
  40503. CylinderGeometry.prototype.copy = function (id) {
  40504. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40505. };
  40506. CylinderGeometry.prototype.serialize = function () {
  40507. var serializationObject = _super.prototype.serialize.call(this);
  40508. serializationObject.height = this.height;
  40509. serializationObject.diameterTop = this.diameterTop;
  40510. serializationObject.diameterBottom = this.diameterBottom;
  40511. serializationObject.tessellation = this.tessellation;
  40512. return serializationObject;
  40513. };
  40514. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40515. if (scene.getGeometryByID(parsedCylinder.id)) {
  40516. return null; // null since geometry could be something else than a cylinder...
  40517. }
  40518. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40519. if (BABYLON.Tags) {
  40520. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40521. }
  40522. scene.pushGeometry(cylinder, true);
  40523. return cylinder;
  40524. };
  40525. return CylinderGeometry;
  40526. }(_PrimitiveGeometry));
  40527. BABYLON.CylinderGeometry = CylinderGeometry;
  40528. /**
  40529. * Creates a new torus geometry
  40530. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40531. */
  40532. var TorusGeometry = /** @class */ (function (_super) {
  40533. __extends(TorusGeometry, _super);
  40534. /**
  40535. * Creates a new torus geometry
  40536. * @param id defines the unique ID of the geometry
  40537. * @param scene defines the hosting scene
  40538. * @param diameter defines the diameter of the torus
  40539. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40540. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40541. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40542. * @param mesh defines the hosting mesh (can be null)
  40543. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40544. */
  40545. function TorusGeometry(id, scene,
  40546. /**
  40547. * Defines the diameter of the torus
  40548. */
  40549. diameter,
  40550. /**
  40551. * Defines the thickness of the torus (ie. internal diameter)
  40552. */
  40553. thickness,
  40554. /**
  40555. * Defines the tesselation factor to apply to the torus
  40556. */
  40557. tessellation, canBeRegenerated, mesh,
  40558. /**
  40559. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40560. */
  40561. side) {
  40562. if (mesh === void 0) { mesh = null; }
  40563. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40564. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40565. _this.diameter = diameter;
  40566. _this.thickness = thickness;
  40567. _this.tessellation = tessellation;
  40568. _this.side = side;
  40569. return _this;
  40570. }
  40571. TorusGeometry.prototype._regenerateVertexData = function () {
  40572. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40573. };
  40574. TorusGeometry.prototype.copy = function (id) {
  40575. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40576. };
  40577. TorusGeometry.prototype.serialize = function () {
  40578. var serializationObject = _super.prototype.serialize.call(this);
  40579. serializationObject.diameter = this.diameter;
  40580. serializationObject.thickness = this.thickness;
  40581. serializationObject.tessellation = this.tessellation;
  40582. return serializationObject;
  40583. };
  40584. TorusGeometry.Parse = function (parsedTorus, scene) {
  40585. if (scene.getGeometryByID(parsedTorus.id)) {
  40586. return null; // null since geometry could be something else than a torus...
  40587. }
  40588. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40589. if (BABYLON.Tags) {
  40590. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40591. }
  40592. scene.pushGeometry(torus, true);
  40593. return torus;
  40594. };
  40595. return TorusGeometry;
  40596. }(_PrimitiveGeometry));
  40597. BABYLON.TorusGeometry = TorusGeometry;
  40598. /**
  40599. * Creates a new ground geometry
  40600. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40601. */
  40602. var GroundGeometry = /** @class */ (function (_super) {
  40603. __extends(GroundGeometry, _super);
  40604. /**
  40605. * Creates a new ground geometry
  40606. * @param id defines the unique ID of the geometry
  40607. * @param scene defines the hosting scene
  40608. * @param width defines the width of the ground
  40609. * @param height defines the height of the ground
  40610. * @param subdivisions defines the subdivisions to apply to the ground
  40611. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40612. * @param mesh defines the hosting mesh (can be null)
  40613. */
  40614. function GroundGeometry(id, scene,
  40615. /**
  40616. * Defines the width of the ground
  40617. */
  40618. width,
  40619. /**
  40620. * Defines the height of the ground
  40621. */
  40622. height,
  40623. /**
  40624. * Defines the subdivisions to apply to the ground
  40625. */
  40626. subdivisions, canBeRegenerated, mesh) {
  40627. if (mesh === void 0) { mesh = null; }
  40628. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40629. _this.width = width;
  40630. _this.height = height;
  40631. _this.subdivisions = subdivisions;
  40632. return _this;
  40633. }
  40634. GroundGeometry.prototype._regenerateVertexData = function () {
  40635. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40636. };
  40637. GroundGeometry.prototype.copy = function (id) {
  40638. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40639. };
  40640. GroundGeometry.prototype.serialize = function () {
  40641. var serializationObject = _super.prototype.serialize.call(this);
  40642. serializationObject.width = this.width;
  40643. serializationObject.height = this.height;
  40644. serializationObject.subdivisions = this.subdivisions;
  40645. return serializationObject;
  40646. };
  40647. GroundGeometry.Parse = function (parsedGround, scene) {
  40648. if (scene.getGeometryByID(parsedGround.id)) {
  40649. return null; // null since geometry could be something else than a ground...
  40650. }
  40651. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40652. if (BABYLON.Tags) {
  40653. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40654. }
  40655. scene.pushGeometry(ground, true);
  40656. return ground;
  40657. };
  40658. return GroundGeometry;
  40659. }(_PrimitiveGeometry));
  40660. BABYLON.GroundGeometry = GroundGeometry;
  40661. /**
  40662. * Creates a tiled ground geometry
  40663. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40664. */
  40665. var TiledGroundGeometry = /** @class */ (function (_super) {
  40666. __extends(TiledGroundGeometry, _super);
  40667. /**
  40668. * Creates a tiled ground geometry
  40669. * @param id defines the unique ID of the geometry
  40670. * @param scene defines the hosting scene
  40671. * @param xmin defines the minimum value on X axis
  40672. * @param zmin defines the minimum value on Z axis
  40673. * @param xmax defines the maximum value on X axis
  40674. * @param zmax defines the maximum value on Z axis
  40675. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40676. * @param precision defines the precision to use when computing the tiles
  40677. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40678. * @param mesh defines the hosting mesh (can be null)
  40679. */
  40680. function TiledGroundGeometry(id, scene,
  40681. /**
  40682. * Defines the minimum value on X axis
  40683. */
  40684. xmin,
  40685. /**
  40686. * Defines the minimum value on Z axis
  40687. */
  40688. zmin,
  40689. /**
  40690. * Defines the maximum value on X axis
  40691. */
  40692. xmax,
  40693. /**
  40694. * Defines the maximum value on Z axis
  40695. */
  40696. zmax,
  40697. /**
  40698. * Defines the subdivisions to apply to the ground
  40699. */
  40700. subdivisions,
  40701. /**
  40702. * Defines the precision to use when computing the tiles
  40703. */
  40704. precision, canBeRegenerated, mesh) {
  40705. if (mesh === void 0) { mesh = null; }
  40706. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40707. _this.xmin = xmin;
  40708. _this.zmin = zmin;
  40709. _this.xmax = xmax;
  40710. _this.zmax = zmax;
  40711. _this.subdivisions = subdivisions;
  40712. _this.precision = precision;
  40713. return _this;
  40714. }
  40715. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40716. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40717. };
  40718. TiledGroundGeometry.prototype.copy = function (id) {
  40719. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40720. };
  40721. return TiledGroundGeometry;
  40722. }(_PrimitiveGeometry));
  40723. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40724. /**
  40725. * Creates a plane geometry
  40726. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40727. */
  40728. var PlaneGeometry = /** @class */ (function (_super) {
  40729. __extends(PlaneGeometry, _super);
  40730. /**
  40731. * Creates a plane geometry
  40732. * @param id defines the unique ID of the geometry
  40733. * @param scene defines the hosting scene
  40734. * @param size defines the size of the plane (width === height)
  40735. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40736. * @param mesh defines the hosting mesh (can be null)
  40737. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40738. */
  40739. function PlaneGeometry(id, scene,
  40740. /**
  40741. * Defines the size of the plane (width === height)
  40742. */
  40743. size, canBeRegenerated, mesh,
  40744. /**
  40745. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40746. */
  40747. side) {
  40748. if (mesh === void 0) { mesh = null; }
  40749. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40750. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40751. _this.size = size;
  40752. _this.side = side;
  40753. return _this;
  40754. }
  40755. PlaneGeometry.prototype._regenerateVertexData = function () {
  40756. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40757. };
  40758. PlaneGeometry.prototype.copy = function (id) {
  40759. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40760. };
  40761. PlaneGeometry.prototype.serialize = function () {
  40762. var serializationObject = _super.prototype.serialize.call(this);
  40763. serializationObject.size = this.size;
  40764. return serializationObject;
  40765. };
  40766. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40767. if (scene.getGeometryByID(parsedPlane.id)) {
  40768. return null; // null since geometry could be something else than a ground...
  40769. }
  40770. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40771. if (BABYLON.Tags) {
  40772. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40773. }
  40774. scene.pushGeometry(plane, true);
  40775. return plane;
  40776. };
  40777. return PlaneGeometry;
  40778. }(_PrimitiveGeometry));
  40779. BABYLON.PlaneGeometry = PlaneGeometry;
  40780. /**
  40781. * Creates a torus knot geometry
  40782. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40783. */
  40784. var TorusKnotGeometry = /** @class */ (function (_super) {
  40785. __extends(TorusKnotGeometry, _super);
  40786. /**
  40787. * Creates a torus knot geometry
  40788. * @param id defines the unique ID of the geometry
  40789. * @param scene defines the hosting scene
  40790. * @param radius defines the radius of the torus knot
  40791. * @param tube defines the thickness of the torus knot tube
  40792. * @param radialSegments defines the number of radial segments
  40793. * @param tubularSegments defines the number of tubular segments
  40794. * @param p defines the first number of windings
  40795. * @param q defines the second number of windings
  40796. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40797. * @param mesh defines the hosting mesh (can be null)
  40798. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40799. */
  40800. function TorusKnotGeometry(id, scene,
  40801. /**
  40802. * Defines the radius of the torus knot
  40803. */
  40804. radius,
  40805. /**
  40806. * Defines the thickness of the torus knot tube
  40807. */
  40808. tube,
  40809. /**
  40810. * Defines the number of radial segments
  40811. */
  40812. radialSegments,
  40813. /**
  40814. * Defines the number of tubular segments
  40815. */
  40816. tubularSegments,
  40817. /**
  40818. * Defines the first number of windings
  40819. */
  40820. p,
  40821. /**
  40822. * Defines the second number of windings
  40823. */
  40824. q, canBeRegenerated, mesh,
  40825. /**
  40826. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40827. */
  40828. side) {
  40829. if (mesh === void 0) { mesh = null; }
  40830. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40831. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40832. _this.radius = radius;
  40833. _this.tube = tube;
  40834. _this.radialSegments = radialSegments;
  40835. _this.tubularSegments = tubularSegments;
  40836. _this.p = p;
  40837. _this.q = q;
  40838. _this.side = side;
  40839. return _this;
  40840. }
  40841. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40842. 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 });
  40843. };
  40844. TorusKnotGeometry.prototype.copy = function (id) {
  40845. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40846. };
  40847. TorusKnotGeometry.prototype.serialize = function () {
  40848. var serializationObject = _super.prototype.serialize.call(this);
  40849. serializationObject.radius = this.radius;
  40850. serializationObject.tube = this.tube;
  40851. serializationObject.radialSegments = this.radialSegments;
  40852. serializationObject.tubularSegments = this.tubularSegments;
  40853. serializationObject.p = this.p;
  40854. serializationObject.q = this.q;
  40855. return serializationObject;
  40856. };
  40857. ;
  40858. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40859. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40860. return null; // null since geometry could be something else than a ground...
  40861. }
  40862. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40863. if (BABYLON.Tags) {
  40864. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40865. }
  40866. scene.pushGeometry(torusKnot, true);
  40867. return torusKnot;
  40868. };
  40869. return TorusKnotGeometry;
  40870. }(_PrimitiveGeometry));
  40871. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40872. //}
  40873. })(BABYLON || (BABYLON = {}));
  40874. //# sourceMappingURL=babylon.geometry.js.map
  40875. var BABYLON;
  40876. (function (BABYLON) {
  40877. /**
  40878. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40879. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40880. */
  40881. var PostProcessManager = /** @class */ (function () {
  40882. /**
  40883. * Creates a new instance PostProcess
  40884. * @param scene The scene that the post process is associated with.
  40885. */
  40886. function PostProcessManager(scene) {
  40887. this._vertexBuffers = {};
  40888. this._scene = scene;
  40889. }
  40890. PostProcessManager.prototype._prepareBuffers = function () {
  40891. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40892. return;
  40893. }
  40894. // VBO
  40895. var vertices = [];
  40896. vertices.push(1, 1);
  40897. vertices.push(-1, 1);
  40898. vertices.push(-1, -1);
  40899. vertices.push(1, -1);
  40900. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40901. this._buildIndexBuffer();
  40902. };
  40903. PostProcessManager.prototype._buildIndexBuffer = function () {
  40904. // Indices
  40905. var indices = [];
  40906. indices.push(0);
  40907. indices.push(1);
  40908. indices.push(2);
  40909. indices.push(0);
  40910. indices.push(2);
  40911. indices.push(3);
  40912. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40913. };
  40914. /**
  40915. * Rebuilds the vertex buffers of the manager.
  40916. */
  40917. PostProcessManager.prototype._rebuild = function () {
  40918. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40919. if (!vb) {
  40920. return;
  40921. }
  40922. vb._rebuild();
  40923. this._buildIndexBuffer();
  40924. };
  40925. // Methods
  40926. /**
  40927. * Prepares a frame to be run through a post process.
  40928. * @param sourceTexture The input texture to the post procesess. (default: null)
  40929. * @param postProcesses An array of post processes to be run. (default: null)
  40930. * @returns True if the post processes were able to be run.
  40931. */
  40932. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40933. if (sourceTexture === void 0) { sourceTexture = null; }
  40934. if (postProcesses === void 0) { postProcesses = null; }
  40935. var camera = this._scene.activeCamera;
  40936. if (!camera) {
  40937. return false;
  40938. }
  40939. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40940. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40941. return false;
  40942. }
  40943. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40944. return true;
  40945. };
  40946. /**
  40947. * Manually render a set of post processes to a texture.
  40948. * @param postProcesses An array of post processes to be run.
  40949. * @param targetTexture The target texture to render to.
  40950. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40951. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  40952. * @param lodLevel defines which lod of the texture to render to
  40953. */
  40954. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  40955. if (targetTexture === void 0) { targetTexture = null; }
  40956. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40957. if (faceIndex === void 0) { faceIndex = 0; }
  40958. if (lodLevel === void 0) { lodLevel = 0; }
  40959. var engine = this._scene.getEngine();
  40960. for (var index = 0; index < postProcesses.length; index++) {
  40961. if (index < postProcesses.length - 1) {
  40962. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40963. }
  40964. else {
  40965. if (targetTexture) {
  40966. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  40967. }
  40968. else {
  40969. engine.restoreDefaultFramebuffer();
  40970. }
  40971. }
  40972. var pp = postProcesses[index];
  40973. var effect = pp.apply();
  40974. if (effect) {
  40975. pp.onBeforeRenderObservable.notifyObservers(effect);
  40976. // VBOs
  40977. this._prepareBuffers();
  40978. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40979. // Draw order
  40980. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40981. pp.onAfterRenderObservable.notifyObservers(effect);
  40982. }
  40983. }
  40984. // Restore depth buffer
  40985. engine.setDepthBuffer(true);
  40986. engine.setDepthWrite(true);
  40987. };
  40988. /**
  40989. * Finalize the result of the output of the postprocesses.
  40990. * @param doNotPresent If true the result will not be displayed to the screen.
  40991. * @param targetTexture The target texture to render to.
  40992. * @param faceIndex The index of the face to bind the target texture to.
  40993. * @param postProcesses The array of post processes to render.
  40994. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40995. */
  40996. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40997. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40998. var camera = this._scene.activeCamera;
  40999. if (!camera) {
  41000. return;
  41001. }
  41002. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  41003. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  41004. return;
  41005. }
  41006. var engine = this._scene.getEngine();
  41007. for (var index = 0, len = postProcesses.length; index < len; index++) {
  41008. var pp = postProcesses[index];
  41009. if (index < len - 1) {
  41010. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  41011. }
  41012. else {
  41013. if (targetTexture) {
  41014. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  41015. pp._outputTexture = targetTexture;
  41016. }
  41017. else {
  41018. engine.restoreDefaultFramebuffer();
  41019. pp._outputTexture = null;
  41020. }
  41021. }
  41022. if (doNotPresent) {
  41023. break;
  41024. }
  41025. var effect = pp.apply();
  41026. if (effect) {
  41027. pp.onBeforeRenderObservable.notifyObservers(effect);
  41028. // VBOs
  41029. this._prepareBuffers();
  41030. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41031. // Draw order
  41032. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  41033. pp.onAfterRenderObservable.notifyObservers(effect);
  41034. }
  41035. }
  41036. // Restore states
  41037. engine.setDepthBuffer(true);
  41038. engine.setDepthWrite(true);
  41039. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41040. };
  41041. /**
  41042. * Disposes of the post process manager.
  41043. */
  41044. PostProcessManager.prototype.dispose = function () {
  41045. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  41046. if (buffer) {
  41047. buffer.dispose();
  41048. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  41049. }
  41050. if (this._indexBuffer) {
  41051. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41052. this._indexBuffer = null;
  41053. }
  41054. };
  41055. return PostProcessManager;
  41056. }());
  41057. BABYLON.PostProcessManager = PostProcessManager;
  41058. })(BABYLON || (BABYLON = {}));
  41059. //# sourceMappingURL=babylon.postProcessManager.js.map
  41060. var BABYLON;
  41061. (function (BABYLON) {
  41062. /**
  41063. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41064. */
  41065. var PerformanceMonitor = /** @class */ (function () {
  41066. /**
  41067. * constructor
  41068. * @param frameSampleSize The number of samples required to saturate the sliding window
  41069. */
  41070. function PerformanceMonitor(frameSampleSize) {
  41071. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41072. this._enabled = true;
  41073. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41074. }
  41075. /**
  41076. * Samples current frame
  41077. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41078. */
  41079. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41080. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41081. if (!this._enabled)
  41082. return;
  41083. if (this._lastFrameTimeMs != null) {
  41084. var dt = timeMs - this._lastFrameTimeMs;
  41085. this._rollingFrameTime.add(dt);
  41086. }
  41087. this._lastFrameTimeMs = timeMs;
  41088. };
  41089. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41090. /**
  41091. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41092. * @return Average frame time in milliseconds
  41093. */
  41094. get: function () {
  41095. return this._rollingFrameTime.average;
  41096. },
  41097. enumerable: true,
  41098. configurable: true
  41099. });
  41100. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41101. /**
  41102. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41103. * @return Frame time variance in milliseconds squared
  41104. */
  41105. get: function () {
  41106. return this._rollingFrameTime.variance;
  41107. },
  41108. enumerable: true,
  41109. configurable: true
  41110. });
  41111. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41112. /**
  41113. * Returns the frame time of the most recent frame
  41114. * @return Frame time in milliseconds
  41115. */
  41116. get: function () {
  41117. return this._rollingFrameTime.history(0);
  41118. },
  41119. enumerable: true,
  41120. configurable: true
  41121. });
  41122. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41123. /**
  41124. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41125. * @return Framerate in frames per second
  41126. */
  41127. get: function () {
  41128. return 1000.0 / this._rollingFrameTime.average;
  41129. },
  41130. enumerable: true,
  41131. configurable: true
  41132. });
  41133. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41134. /**
  41135. * Returns the average framerate in frames per second using the most recent frame time
  41136. * @return Framerate in frames per second
  41137. */
  41138. get: function () {
  41139. var history = this._rollingFrameTime.history(0);
  41140. if (history === 0) {
  41141. return 0;
  41142. }
  41143. return 1000.0 / history;
  41144. },
  41145. enumerable: true,
  41146. configurable: true
  41147. });
  41148. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41149. /**
  41150. * Returns true if enough samples have been taken to completely fill the sliding window
  41151. * @return true if saturated
  41152. */
  41153. get: function () {
  41154. return this._rollingFrameTime.isSaturated();
  41155. },
  41156. enumerable: true,
  41157. configurable: true
  41158. });
  41159. /**
  41160. * Enables contributions to the sliding window sample set
  41161. */
  41162. PerformanceMonitor.prototype.enable = function () {
  41163. this._enabled = true;
  41164. };
  41165. /**
  41166. * Disables contributions to the sliding window sample set
  41167. * Samples will not be interpolated over the disabled period
  41168. */
  41169. PerformanceMonitor.prototype.disable = function () {
  41170. this._enabled = false;
  41171. //clear last sample to avoid interpolating over the disabled period when next enabled
  41172. this._lastFrameTimeMs = null;
  41173. };
  41174. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41175. /**
  41176. * Returns true if sampling is enabled
  41177. * @return true if enabled
  41178. */
  41179. get: function () {
  41180. return this._enabled;
  41181. },
  41182. enumerable: true,
  41183. configurable: true
  41184. });
  41185. /**
  41186. * Resets performance monitor
  41187. */
  41188. PerformanceMonitor.prototype.reset = function () {
  41189. //clear last sample to avoid interpolating over the disabled period when next enabled
  41190. this._lastFrameTimeMs = null;
  41191. //wipe record
  41192. this._rollingFrameTime.reset();
  41193. };
  41194. return PerformanceMonitor;
  41195. }());
  41196. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41197. /**
  41198. * RollingAverage
  41199. *
  41200. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41201. */
  41202. var RollingAverage = /** @class */ (function () {
  41203. /**
  41204. * constructor
  41205. * @param length The number of samples required to saturate the sliding window
  41206. */
  41207. function RollingAverage(length) {
  41208. this._samples = new Array(length);
  41209. this.reset();
  41210. }
  41211. /**
  41212. * Adds a sample to the sample set
  41213. * @param v The sample value
  41214. */
  41215. RollingAverage.prototype.add = function (v) {
  41216. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41217. var delta;
  41218. //we need to check if we've already wrapped round
  41219. if (this.isSaturated()) {
  41220. //remove bottom of stack from mean
  41221. var bottomValue = this._samples[this._pos];
  41222. delta = bottomValue - this.average;
  41223. this.average -= delta / (this._sampleCount - 1);
  41224. this._m2 -= delta * (bottomValue - this.average);
  41225. }
  41226. else {
  41227. this._sampleCount++;
  41228. }
  41229. //add new value to mean
  41230. delta = v - this.average;
  41231. this.average += delta / (this._sampleCount);
  41232. this._m2 += delta * (v - this.average);
  41233. //set the new variance
  41234. this.variance = this._m2 / (this._sampleCount - 1);
  41235. this._samples[this._pos] = v;
  41236. this._pos++;
  41237. this._pos %= this._samples.length; //positive wrap around
  41238. };
  41239. /**
  41240. * Returns previously added values or null if outside of history or outside the sliding window domain
  41241. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41242. * @return Value previously recorded with add() or null if outside of range
  41243. */
  41244. RollingAverage.prototype.history = function (i) {
  41245. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41246. return 0;
  41247. }
  41248. var i0 = this._wrapPosition(this._pos - 1.0);
  41249. return this._samples[this._wrapPosition(i0 - i)];
  41250. };
  41251. /**
  41252. * Returns true if enough samples have been taken to completely fill the sliding window
  41253. * @return true if sample-set saturated
  41254. */
  41255. RollingAverage.prototype.isSaturated = function () {
  41256. return this._sampleCount >= this._samples.length;
  41257. };
  41258. /**
  41259. * Resets the rolling average (equivalent to 0 samples taken so far)
  41260. */
  41261. RollingAverage.prototype.reset = function () {
  41262. this.average = 0;
  41263. this.variance = 0;
  41264. this._sampleCount = 0;
  41265. this._pos = 0;
  41266. this._m2 = 0;
  41267. };
  41268. /**
  41269. * Wraps a value around the sample range boundaries
  41270. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41271. * @return Wrapped position in sample range
  41272. */
  41273. RollingAverage.prototype._wrapPosition = function (i) {
  41274. var max = this._samples.length;
  41275. return ((i % max) + max) % max;
  41276. };
  41277. return RollingAverage;
  41278. }());
  41279. BABYLON.RollingAverage = RollingAverage;
  41280. })(BABYLON || (BABYLON = {}));
  41281. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41282. var BABYLON;
  41283. (function (BABYLON) {
  41284. /**
  41285. * This groups together the common properties used for image processing either in direct forward pass
  41286. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41287. * or not.
  41288. */
  41289. var ImageProcessingConfiguration = /** @class */ (function () {
  41290. function ImageProcessingConfiguration() {
  41291. /**
  41292. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41293. */
  41294. this.colorCurves = new BABYLON.ColorCurves();
  41295. this._colorCurvesEnabled = false;
  41296. this._colorGradingEnabled = false;
  41297. this._colorGradingWithGreenDepth = true;
  41298. this._colorGradingBGR = true;
  41299. this._exposure = 1.0;
  41300. this._toneMappingEnabled = false;
  41301. this._contrast = 1.0;
  41302. /**
  41303. * Vignette stretch size.
  41304. */
  41305. this.vignetteStretch = 0;
  41306. /**
  41307. * Vignette centre X Offset.
  41308. */
  41309. this.vignetteCentreX = 0;
  41310. /**
  41311. * Vignette centre Y Offset.
  41312. */
  41313. this.vignetteCentreY = 0;
  41314. /**
  41315. * Vignette weight or intensity of the vignette effect.
  41316. */
  41317. this.vignetteWeight = 1.5;
  41318. /**
  41319. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41320. * if vignetteEnabled is set to true.
  41321. */
  41322. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41323. /**
  41324. * Camera field of view used by the Vignette effect.
  41325. */
  41326. this.vignetteCameraFov = 0.5;
  41327. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41328. this._vignetteEnabled = false;
  41329. this._applyByPostProcess = false;
  41330. this._isEnabled = true;
  41331. /**
  41332. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41333. */
  41334. this.onUpdateParameters = new BABYLON.Observable();
  41335. }
  41336. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41337. /**
  41338. * Gets wether the color curves effect is enabled.
  41339. */
  41340. get: function () {
  41341. return this._colorCurvesEnabled;
  41342. },
  41343. /**
  41344. * Sets wether the color curves effect is enabled.
  41345. */
  41346. set: function (value) {
  41347. if (this._colorCurvesEnabled === value) {
  41348. return;
  41349. }
  41350. this._colorCurvesEnabled = value;
  41351. this._updateParameters();
  41352. },
  41353. enumerable: true,
  41354. configurable: true
  41355. });
  41356. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41357. /**
  41358. * Gets wether the color grading effect is enabled.
  41359. */
  41360. get: function () {
  41361. return this._colorGradingEnabled;
  41362. },
  41363. /**
  41364. * Sets wether the color grading effect is enabled.
  41365. */
  41366. set: function (value) {
  41367. if (this._colorGradingEnabled === value) {
  41368. return;
  41369. }
  41370. this._colorGradingEnabled = value;
  41371. this._updateParameters();
  41372. },
  41373. enumerable: true,
  41374. configurable: true
  41375. });
  41376. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41377. /**
  41378. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41379. */
  41380. get: function () {
  41381. return this._colorGradingWithGreenDepth;
  41382. },
  41383. /**
  41384. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41385. */
  41386. set: function (value) {
  41387. if (this._colorGradingWithGreenDepth === value) {
  41388. return;
  41389. }
  41390. this._colorGradingWithGreenDepth = value;
  41391. this._updateParameters();
  41392. },
  41393. enumerable: true,
  41394. configurable: true
  41395. });
  41396. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41397. /**
  41398. * Gets wether the color grading texture contains BGR values.
  41399. */
  41400. get: function () {
  41401. return this._colorGradingBGR;
  41402. },
  41403. /**
  41404. * Sets wether the color grading texture contains BGR values.
  41405. */
  41406. set: function (value) {
  41407. if (this._colorGradingBGR === value) {
  41408. return;
  41409. }
  41410. this._colorGradingBGR = value;
  41411. this._updateParameters();
  41412. },
  41413. enumerable: true,
  41414. configurable: true
  41415. });
  41416. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41417. /**
  41418. * Gets the Exposure used in the effect.
  41419. */
  41420. get: function () {
  41421. return this._exposure;
  41422. },
  41423. /**
  41424. * Sets the Exposure used in the effect.
  41425. */
  41426. set: function (value) {
  41427. if (this._exposure === value) {
  41428. return;
  41429. }
  41430. this._exposure = value;
  41431. this._updateParameters();
  41432. },
  41433. enumerable: true,
  41434. configurable: true
  41435. });
  41436. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41437. /**
  41438. * Gets wether the tone mapping effect is enabled.
  41439. */
  41440. get: function () {
  41441. return this._toneMappingEnabled;
  41442. },
  41443. /**
  41444. * Sets wether the tone mapping effect is enabled.
  41445. */
  41446. set: function (value) {
  41447. if (this._toneMappingEnabled === value) {
  41448. return;
  41449. }
  41450. this._toneMappingEnabled = value;
  41451. this._updateParameters();
  41452. },
  41453. enumerable: true,
  41454. configurable: true
  41455. });
  41456. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41457. /**
  41458. * Gets the contrast used in the effect.
  41459. */
  41460. get: function () {
  41461. return this._contrast;
  41462. },
  41463. /**
  41464. * Sets the contrast used in the effect.
  41465. */
  41466. set: function (value) {
  41467. if (this._contrast === value) {
  41468. return;
  41469. }
  41470. this._contrast = value;
  41471. this._updateParameters();
  41472. },
  41473. enumerable: true,
  41474. configurable: true
  41475. });
  41476. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41477. /**
  41478. * Gets the vignette blend mode allowing different kind of effect.
  41479. */
  41480. get: function () {
  41481. return this._vignetteBlendMode;
  41482. },
  41483. /**
  41484. * Sets the vignette blend mode allowing different kind of effect.
  41485. */
  41486. set: function (value) {
  41487. if (this._vignetteBlendMode === value) {
  41488. return;
  41489. }
  41490. this._vignetteBlendMode = value;
  41491. this._updateParameters();
  41492. },
  41493. enumerable: true,
  41494. configurable: true
  41495. });
  41496. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41497. /**
  41498. * Gets wether the vignette effect is enabled.
  41499. */
  41500. get: function () {
  41501. return this._vignetteEnabled;
  41502. },
  41503. /**
  41504. * Sets wether the vignette effect is enabled.
  41505. */
  41506. set: function (value) {
  41507. if (this._vignetteEnabled === value) {
  41508. return;
  41509. }
  41510. this._vignetteEnabled = value;
  41511. this._updateParameters();
  41512. },
  41513. enumerable: true,
  41514. configurable: true
  41515. });
  41516. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41517. /**
  41518. * Gets wether the image processing is applied through a post process or not.
  41519. */
  41520. get: function () {
  41521. return this._applyByPostProcess;
  41522. },
  41523. /**
  41524. * Sets wether the image processing is applied through a post process or not.
  41525. */
  41526. set: function (value) {
  41527. if (this._applyByPostProcess === value) {
  41528. return;
  41529. }
  41530. this._applyByPostProcess = value;
  41531. this._updateParameters();
  41532. },
  41533. enumerable: true,
  41534. configurable: true
  41535. });
  41536. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41537. /**
  41538. * Gets wether the image processing is enabled or not.
  41539. */
  41540. get: function () {
  41541. return this._isEnabled;
  41542. },
  41543. /**
  41544. * Sets wether the image processing is enabled or not.
  41545. */
  41546. set: function (value) {
  41547. if (this._isEnabled === value) {
  41548. return;
  41549. }
  41550. this._isEnabled = value;
  41551. this._updateParameters();
  41552. },
  41553. enumerable: true,
  41554. configurable: true
  41555. });
  41556. /**
  41557. * Method called each time the image processing information changes requires to recompile the effect.
  41558. */
  41559. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41560. this.onUpdateParameters.notifyObservers(this);
  41561. };
  41562. ImageProcessingConfiguration.prototype.getClassName = function () {
  41563. return "ImageProcessingConfiguration";
  41564. };
  41565. /**
  41566. * Prepare the list of uniforms associated with the Image Processing effects.
  41567. * @param uniformsList The list of uniforms used in the effect
  41568. * @param defines the list of defines currently in use
  41569. */
  41570. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41571. if (defines.EXPOSURE) {
  41572. uniforms.push("exposureLinear");
  41573. }
  41574. if (defines.CONTRAST) {
  41575. uniforms.push("contrast");
  41576. }
  41577. if (defines.COLORGRADING) {
  41578. uniforms.push("colorTransformSettings");
  41579. }
  41580. if (defines.VIGNETTE) {
  41581. uniforms.push("vInverseScreenSize");
  41582. uniforms.push("vignetteSettings1");
  41583. uniforms.push("vignetteSettings2");
  41584. }
  41585. if (defines.COLORCURVES) {
  41586. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41587. }
  41588. };
  41589. /**
  41590. * Prepare the list of samplers associated with the Image Processing effects.
  41591. * @param uniformsList The list of uniforms used in the effect
  41592. * @param defines the list of defines currently in use
  41593. */
  41594. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41595. if (defines.COLORGRADING) {
  41596. samplersList.push("txColorTransform");
  41597. }
  41598. };
  41599. /**
  41600. * Prepare the list of defines associated to the shader.
  41601. * @param defines the list of defines to complete
  41602. */
  41603. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41604. if (forPostProcess === void 0) { forPostProcess = false; }
  41605. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41606. defines.VIGNETTE = false;
  41607. defines.TONEMAPPING = false;
  41608. defines.CONTRAST = false;
  41609. defines.EXPOSURE = false;
  41610. defines.COLORCURVES = false;
  41611. defines.COLORGRADING = false;
  41612. defines.COLORGRADING3D = false;
  41613. defines.IMAGEPROCESSING = false;
  41614. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41615. return;
  41616. }
  41617. defines.VIGNETTE = this.vignetteEnabled;
  41618. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41619. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41620. defines.TONEMAPPING = this.toneMappingEnabled;
  41621. defines.CONTRAST = (this.contrast !== 1.0);
  41622. defines.EXPOSURE = (this.exposure !== 1.0);
  41623. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41624. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41625. if (defines.COLORGRADING) {
  41626. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41627. }
  41628. else {
  41629. defines.COLORGRADING3D = false;
  41630. }
  41631. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41632. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41633. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41634. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41635. };
  41636. /**
  41637. * Returns true if all the image processing information are ready.
  41638. */
  41639. ImageProcessingConfiguration.prototype.isReady = function () {
  41640. // Color Grading texure can not be none blocking.
  41641. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41642. };
  41643. /**
  41644. * Binds the image processing to the shader.
  41645. * @param effect The effect to bind to
  41646. */
  41647. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41648. if (aspectRatio === void 0) { aspectRatio = 1; }
  41649. // Color Curves
  41650. if (this._colorCurvesEnabled && this.colorCurves) {
  41651. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41652. }
  41653. // Vignette
  41654. if (this._vignetteEnabled) {
  41655. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41656. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41657. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41658. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41659. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41660. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41661. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41662. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41663. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41664. var vignettePower = -2.0 * this.vignetteWeight;
  41665. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41666. }
  41667. // Exposure
  41668. effect.setFloat("exposureLinear", this.exposure);
  41669. // Contrast
  41670. effect.setFloat("contrast", this.contrast);
  41671. // Color transform settings
  41672. if (this.colorGradingTexture) {
  41673. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41674. var textureSize = this.colorGradingTexture.getSize().height;
  41675. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41676. 0.5 / textureSize, // textureOffset
  41677. textureSize, // textureSize
  41678. this.colorGradingTexture.level // weight
  41679. );
  41680. }
  41681. };
  41682. /**
  41683. * Clones the current image processing instance.
  41684. * @return The cloned image processing
  41685. */
  41686. ImageProcessingConfiguration.prototype.clone = function () {
  41687. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41688. };
  41689. /**
  41690. * Serializes the current image processing instance to a json representation.
  41691. * @return a JSON representation
  41692. */
  41693. ImageProcessingConfiguration.prototype.serialize = function () {
  41694. return BABYLON.SerializationHelper.Serialize(this);
  41695. };
  41696. /**
  41697. * Parses the image processing from a json representation.
  41698. * @param source the JSON source to parse
  41699. * @return The parsed image processing
  41700. */
  41701. ImageProcessingConfiguration.Parse = function (source) {
  41702. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41703. };
  41704. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41705. /**
  41706. * Used to apply the vignette as a mix with the pixel color.
  41707. */
  41708. get: function () {
  41709. return this._VIGNETTEMODE_MULTIPLY;
  41710. },
  41711. enumerable: true,
  41712. configurable: true
  41713. });
  41714. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41715. /**
  41716. * Used to apply the vignette as a replacement of the pixel color.
  41717. */
  41718. get: function () {
  41719. return this._VIGNETTEMODE_OPAQUE;
  41720. },
  41721. enumerable: true,
  41722. configurable: true
  41723. });
  41724. // Static constants associated to the image processing.
  41725. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41726. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41727. __decorate([
  41728. BABYLON.serializeAsColorCurves()
  41729. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41730. __decorate([
  41731. BABYLON.serialize()
  41732. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41733. __decorate([
  41734. BABYLON.serializeAsTexture()
  41735. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41736. __decorate([
  41737. BABYLON.serialize()
  41738. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41739. __decorate([
  41740. BABYLON.serialize()
  41741. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41742. __decorate([
  41743. BABYLON.serialize()
  41744. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41745. __decorate([
  41746. BABYLON.serialize()
  41747. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41748. __decorate([
  41749. BABYLON.serialize()
  41750. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41751. __decorate([
  41752. BABYLON.serialize()
  41753. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41754. __decorate([
  41755. BABYLON.serialize()
  41756. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41757. __decorate([
  41758. BABYLON.serialize()
  41759. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41760. __decorate([
  41761. BABYLON.serialize()
  41762. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41763. __decorate([
  41764. BABYLON.serialize()
  41765. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41766. __decorate([
  41767. BABYLON.serializeAsColor4()
  41768. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41769. __decorate([
  41770. BABYLON.serialize()
  41771. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41772. __decorate([
  41773. BABYLON.serialize()
  41774. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41775. __decorate([
  41776. BABYLON.serialize()
  41777. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41778. __decorate([
  41779. BABYLON.serialize()
  41780. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41781. __decorate([
  41782. BABYLON.serialize()
  41783. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41784. return ImageProcessingConfiguration;
  41785. }());
  41786. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41787. })(BABYLON || (BABYLON = {}));
  41788. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41789. var BABYLON;
  41790. (function (BABYLON) {
  41791. /**
  41792. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41793. * It can help converting any input color in a desired output one. This can then be used to create effects
  41794. * from sepia, black and white to sixties or futuristic rendering...
  41795. *
  41796. * The only supported format is currently 3dl.
  41797. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41798. */
  41799. var ColorGradingTexture = /** @class */ (function (_super) {
  41800. __extends(ColorGradingTexture, _super);
  41801. /**
  41802. * Instantiates a ColorGradingTexture from the following parameters.
  41803. *
  41804. * @param url The location of the color gradind data (currently only supporting 3dl)
  41805. * @param scene The scene the texture will be used in
  41806. */
  41807. function ColorGradingTexture(url, scene) {
  41808. var _this = _super.call(this, scene) || this;
  41809. if (!url) {
  41810. return _this;
  41811. }
  41812. _this._engine = scene.getEngine();
  41813. _this._textureMatrix = BABYLON.Matrix.Identity();
  41814. _this.name = url;
  41815. _this.url = url;
  41816. _this.hasAlpha = false;
  41817. _this.isCube = false;
  41818. _this.is3D = _this._engine.webGLVersion > 1;
  41819. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41820. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41821. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41822. _this.anisotropicFilteringLevel = 1;
  41823. _this._texture = _this._getFromCache(url, true);
  41824. if (!_this._texture) {
  41825. if (!scene.useDelayedTextureLoading) {
  41826. _this.loadTexture();
  41827. }
  41828. else {
  41829. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41830. }
  41831. }
  41832. return _this;
  41833. }
  41834. /**
  41835. * Returns the texture matrix used in most of the material.
  41836. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41837. */
  41838. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41839. return this._textureMatrix;
  41840. };
  41841. /**
  41842. * Occurs when the file being loaded is a .3dl LUT file.
  41843. */
  41844. ColorGradingTexture.prototype.load3dlTexture = function () {
  41845. var engine = this._engine;
  41846. var texture;
  41847. if (engine.webGLVersion === 1) {
  41848. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41849. }
  41850. else {
  41851. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41852. }
  41853. this._texture = texture;
  41854. var callback = function (text) {
  41855. if (typeof text !== "string") {
  41856. return;
  41857. }
  41858. var data = null;
  41859. var tempData = null;
  41860. var line;
  41861. var lines = text.split('\n');
  41862. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41863. var maxColor = 0;
  41864. for (var i = 0; i < lines.length; i++) {
  41865. line = lines[i];
  41866. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41867. continue;
  41868. if (line.indexOf('#') === 0)
  41869. continue;
  41870. var words = line.split(" ");
  41871. if (size === 0) {
  41872. // Number of space + one
  41873. size = words.length;
  41874. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41875. tempData = new Float32Array(size * size * size * 4);
  41876. continue;
  41877. }
  41878. if (size != 0) {
  41879. var r = Math.max(parseInt(words[0]), 0);
  41880. var g = Math.max(parseInt(words[1]), 0);
  41881. var b = Math.max(parseInt(words[2]), 0);
  41882. maxColor = Math.max(r, maxColor);
  41883. maxColor = Math.max(g, maxColor);
  41884. maxColor = Math.max(b, maxColor);
  41885. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41886. if (tempData) {
  41887. tempData[pixelStorageIndex + 0] = r;
  41888. tempData[pixelStorageIndex + 1] = g;
  41889. tempData[pixelStorageIndex + 2] = b;
  41890. }
  41891. pixelIndexSlice++;
  41892. if (pixelIndexSlice % size == 0) {
  41893. pixelIndexH++;
  41894. pixelIndexSlice = 0;
  41895. if (pixelIndexH % size == 0) {
  41896. pixelIndexW++;
  41897. pixelIndexH = 0;
  41898. }
  41899. }
  41900. }
  41901. }
  41902. if (tempData && data) {
  41903. for (var i = 0; i < tempData.length; i++) {
  41904. if (i > 0 && (i + 1) % 4 === 0) {
  41905. data[i] = 255;
  41906. }
  41907. else {
  41908. var value = tempData[i];
  41909. data[i] = (value / maxColor * 255);
  41910. }
  41911. }
  41912. }
  41913. if (texture.is3D) {
  41914. texture.updateSize(size, size, size);
  41915. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41916. }
  41917. else {
  41918. texture.updateSize(size * size, size);
  41919. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41920. }
  41921. };
  41922. var scene = this.getScene();
  41923. if (scene) {
  41924. scene._loadFile(this.url, callback);
  41925. }
  41926. else {
  41927. this._engine._loadFile(this.url, callback);
  41928. }
  41929. return this._texture;
  41930. };
  41931. /**
  41932. * Starts the loading process of the texture.
  41933. */
  41934. ColorGradingTexture.prototype.loadTexture = function () {
  41935. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41936. this.load3dlTexture();
  41937. }
  41938. };
  41939. /**
  41940. * Clones the color gradind texture.
  41941. */
  41942. ColorGradingTexture.prototype.clone = function () {
  41943. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41944. // Base texture
  41945. newTexture.level = this.level;
  41946. return newTexture;
  41947. };
  41948. /**
  41949. * Called during delayed load for textures.
  41950. */
  41951. ColorGradingTexture.prototype.delayLoad = function () {
  41952. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41953. return;
  41954. }
  41955. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41956. this._texture = this._getFromCache(this.url, true);
  41957. if (!this._texture) {
  41958. this.loadTexture();
  41959. }
  41960. };
  41961. /**
  41962. * Parses a color grading texture serialized by Babylon.
  41963. * @param parsedTexture The texture information being parsedTexture
  41964. * @param scene The scene to load the texture in
  41965. * @param rootUrl The root url of the data assets to load
  41966. * @return A color gradind texture
  41967. */
  41968. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41969. var texture = null;
  41970. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41971. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41972. texture.name = parsedTexture.name;
  41973. texture.level = parsedTexture.level;
  41974. }
  41975. return texture;
  41976. };
  41977. /**
  41978. * Serializes the LUT texture to json format.
  41979. */
  41980. ColorGradingTexture.prototype.serialize = function () {
  41981. if (!this.name) {
  41982. return null;
  41983. }
  41984. var serializationObject = {};
  41985. serializationObject.name = this.name;
  41986. serializationObject.level = this.level;
  41987. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41988. return serializationObject;
  41989. };
  41990. /**
  41991. * Empty line regex stored for GC.
  41992. */
  41993. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41994. return ColorGradingTexture;
  41995. }(BABYLON.BaseTexture));
  41996. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41997. })(BABYLON || (BABYLON = {}));
  41998. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41999. var BABYLON;
  42000. (function (BABYLON) {
  42001. /**
  42002. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42003. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42004. * 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;
  42005. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42006. */
  42007. var ColorCurves = /** @class */ (function () {
  42008. function ColorCurves() {
  42009. this._dirty = true;
  42010. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  42011. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  42012. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  42013. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  42014. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  42015. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  42016. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  42017. this._globalHue = 30;
  42018. this._globalDensity = 0;
  42019. this._globalSaturation = 0;
  42020. this._globalExposure = 0;
  42021. this._highlightsHue = 30;
  42022. this._highlightsDensity = 0;
  42023. this._highlightsSaturation = 0;
  42024. this._highlightsExposure = 0;
  42025. this._midtonesHue = 30;
  42026. this._midtonesDensity = 0;
  42027. this._midtonesSaturation = 0;
  42028. this._midtonesExposure = 0;
  42029. this._shadowsHue = 30;
  42030. this._shadowsDensity = 0;
  42031. this._shadowsSaturation = 0;
  42032. this._shadowsExposure = 0;
  42033. }
  42034. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  42035. /**
  42036. * Gets the global Hue value.
  42037. * 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).
  42038. */
  42039. get: function () {
  42040. return this._globalHue;
  42041. },
  42042. /**
  42043. * Sets the global Hue value.
  42044. * 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).
  42045. */
  42046. set: function (value) {
  42047. this._globalHue = value;
  42048. this._dirty = true;
  42049. },
  42050. enumerable: true,
  42051. configurable: true
  42052. });
  42053. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  42054. /**
  42055. * Gets the global Density value.
  42056. * 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.
  42057. * Values less than zero provide a filter of opposite hue.
  42058. */
  42059. get: function () {
  42060. return this._globalDensity;
  42061. },
  42062. /**
  42063. * Sets the global Density value.
  42064. * 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.
  42065. * Values less than zero provide a filter of opposite hue.
  42066. */
  42067. set: function (value) {
  42068. this._globalDensity = value;
  42069. this._dirty = true;
  42070. },
  42071. enumerable: true,
  42072. configurable: true
  42073. });
  42074. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  42075. /**
  42076. * Gets the global Saturation value.
  42077. * 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.
  42078. */
  42079. get: function () {
  42080. return this._globalSaturation;
  42081. },
  42082. /**
  42083. * Sets the global Saturation value.
  42084. * 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.
  42085. */
  42086. set: function (value) {
  42087. this._globalSaturation = value;
  42088. this._dirty = true;
  42089. },
  42090. enumerable: true,
  42091. configurable: true
  42092. });
  42093. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  42094. /**
  42095. * Gets the global Exposure value.
  42096. * 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.
  42097. */
  42098. get: function () {
  42099. return this._globalExposure;
  42100. },
  42101. /**
  42102. * Sets the global Exposure value.
  42103. * 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.
  42104. */
  42105. set: function (value) {
  42106. this._globalExposure = value;
  42107. this._dirty = true;
  42108. },
  42109. enumerable: true,
  42110. configurable: true
  42111. });
  42112. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  42113. /**
  42114. * Gets the highlights Hue value.
  42115. * 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).
  42116. */
  42117. get: function () {
  42118. return this._highlightsHue;
  42119. },
  42120. /**
  42121. * Sets the highlights Hue value.
  42122. * 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).
  42123. */
  42124. set: function (value) {
  42125. this._highlightsHue = value;
  42126. this._dirty = true;
  42127. },
  42128. enumerable: true,
  42129. configurable: true
  42130. });
  42131. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  42132. /**
  42133. * Gets the highlights Density value.
  42134. * 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.
  42135. * Values less than zero provide a filter of opposite hue.
  42136. */
  42137. get: function () {
  42138. return this._highlightsDensity;
  42139. },
  42140. /**
  42141. * Sets the highlights Density value.
  42142. * 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.
  42143. * Values less than zero provide a filter of opposite hue.
  42144. */
  42145. set: function (value) {
  42146. this._highlightsDensity = value;
  42147. this._dirty = true;
  42148. },
  42149. enumerable: true,
  42150. configurable: true
  42151. });
  42152. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  42153. /**
  42154. * Gets the highlights Saturation value.
  42155. * 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.
  42156. */
  42157. get: function () {
  42158. return this._highlightsSaturation;
  42159. },
  42160. /**
  42161. * Sets the highlights Saturation value.
  42162. * 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.
  42163. */
  42164. set: function (value) {
  42165. this._highlightsSaturation = value;
  42166. this._dirty = true;
  42167. },
  42168. enumerable: true,
  42169. configurable: true
  42170. });
  42171. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42172. /**
  42173. * Gets the highlights Exposure value.
  42174. * 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.
  42175. */
  42176. get: function () {
  42177. return this._highlightsExposure;
  42178. },
  42179. /**
  42180. * Sets the highlights Exposure value.
  42181. * 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.
  42182. */
  42183. set: function (value) {
  42184. this._highlightsExposure = value;
  42185. this._dirty = true;
  42186. },
  42187. enumerable: true,
  42188. configurable: true
  42189. });
  42190. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42191. /**
  42192. * Gets the midtones Hue value.
  42193. * 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).
  42194. */
  42195. get: function () {
  42196. return this._midtonesHue;
  42197. },
  42198. /**
  42199. * Sets the midtones Hue value.
  42200. * 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).
  42201. */
  42202. set: function (value) {
  42203. this._midtonesHue = value;
  42204. this._dirty = true;
  42205. },
  42206. enumerable: true,
  42207. configurable: true
  42208. });
  42209. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42210. /**
  42211. * Gets the midtones Density value.
  42212. * 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.
  42213. * Values less than zero provide a filter of opposite hue.
  42214. */
  42215. get: function () {
  42216. return this._midtonesDensity;
  42217. },
  42218. /**
  42219. * Sets the midtones Density value.
  42220. * 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.
  42221. * Values less than zero provide a filter of opposite hue.
  42222. */
  42223. set: function (value) {
  42224. this._midtonesDensity = value;
  42225. this._dirty = true;
  42226. },
  42227. enumerable: true,
  42228. configurable: true
  42229. });
  42230. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42231. /**
  42232. * Gets the midtones Saturation value.
  42233. * 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.
  42234. */
  42235. get: function () {
  42236. return this._midtonesSaturation;
  42237. },
  42238. /**
  42239. * Sets the midtones Saturation value.
  42240. * 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.
  42241. */
  42242. set: function (value) {
  42243. this._midtonesSaturation = value;
  42244. this._dirty = true;
  42245. },
  42246. enumerable: true,
  42247. configurable: true
  42248. });
  42249. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42250. /**
  42251. * Gets the midtones Exposure value.
  42252. * 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.
  42253. */
  42254. get: function () {
  42255. return this._midtonesExposure;
  42256. },
  42257. /**
  42258. * Sets the midtones Exposure value.
  42259. * 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.
  42260. */
  42261. set: function (value) {
  42262. this._midtonesExposure = value;
  42263. this._dirty = true;
  42264. },
  42265. enumerable: true,
  42266. configurable: true
  42267. });
  42268. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42269. /**
  42270. * Gets the shadows Hue value.
  42271. * 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).
  42272. */
  42273. get: function () {
  42274. return this._shadowsHue;
  42275. },
  42276. /**
  42277. * Sets the shadows Hue value.
  42278. * 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).
  42279. */
  42280. set: function (value) {
  42281. this._shadowsHue = value;
  42282. this._dirty = true;
  42283. },
  42284. enumerable: true,
  42285. configurable: true
  42286. });
  42287. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42288. /**
  42289. * Gets the shadows Density value.
  42290. * 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.
  42291. * Values less than zero provide a filter of opposite hue.
  42292. */
  42293. get: function () {
  42294. return this._shadowsDensity;
  42295. },
  42296. /**
  42297. * Sets the shadows Density value.
  42298. * 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.
  42299. * Values less than zero provide a filter of opposite hue.
  42300. */
  42301. set: function (value) {
  42302. this._shadowsDensity = value;
  42303. this._dirty = true;
  42304. },
  42305. enumerable: true,
  42306. configurable: true
  42307. });
  42308. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42309. /**
  42310. * Gets the shadows Saturation value.
  42311. * 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.
  42312. */
  42313. get: function () {
  42314. return this._shadowsSaturation;
  42315. },
  42316. /**
  42317. * Sets the shadows Saturation value.
  42318. * 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.
  42319. */
  42320. set: function (value) {
  42321. this._shadowsSaturation = value;
  42322. this._dirty = true;
  42323. },
  42324. enumerable: true,
  42325. configurable: true
  42326. });
  42327. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42328. /**
  42329. * Gets the shadows Exposure value.
  42330. * 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.
  42331. */
  42332. get: function () {
  42333. return this._shadowsExposure;
  42334. },
  42335. /**
  42336. * Sets the shadows Exposure value.
  42337. * 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.
  42338. */
  42339. set: function (value) {
  42340. this._shadowsExposure = value;
  42341. this._dirty = true;
  42342. },
  42343. enumerable: true,
  42344. configurable: true
  42345. });
  42346. ColorCurves.prototype.getClassName = function () {
  42347. return "ColorCurves";
  42348. };
  42349. /**
  42350. * Binds the color curves to the shader.
  42351. * @param colorCurves The color curve to bind
  42352. * @param effect The effect to bind to
  42353. */
  42354. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42355. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42356. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42357. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42358. if (colorCurves._dirty) {
  42359. colorCurves._dirty = false;
  42360. // Fill in global info.
  42361. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42362. // Compute highlights info.
  42363. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42364. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42365. // Compute midtones info.
  42366. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42367. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42368. // Compute shadows info.
  42369. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42370. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42371. // Compute deltas (neutral is midtones).
  42372. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42373. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42374. }
  42375. if (effect) {
  42376. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42377. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42378. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42379. }
  42380. };
  42381. /**
  42382. * Prepare the list of uniforms associated with the ColorCurves effects.
  42383. * @param uniformsList The list of uniforms used in the effect
  42384. */
  42385. ColorCurves.PrepareUniforms = function (uniformsList) {
  42386. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42387. };
  42388. /**
  42389. * Returns color grading data based on a hue, density, saturation and exposure value.
  42390. * @param filterHue The hue of the color filter.
  42391. * @param filterDensity The density of the color filter.
  42392. * @param saturation The saturation.
  42393. * @param exposure The exposure.
  42394. * @param result The result data container.
  42395. */
  42396. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42397. if (hue == null) {
  42398. return;
  42399. }
  42400. hue = ColorCurves.clamp(hue, 0, 360);
  42401. density = ColorCurves.clamp(density, -100, 100);
  42402. saturation = ColorCurves.clamp(saturation, -100, 100);
  42403. exposure = ColorCurves.clamp(exposure, -100, 100);
  42404. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42405. // so that the maximum filter density is only 50% control. This provides fine control
  42406. // for small values and reasonable range.
  42407. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42408. density *= 0.5;
  42409. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42410. if (density < 0) {
  42411. density *= -1;
  42412. hue = (hue + 180) % 360;
  42413. }
  42414. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42415. result.scaleToRef(2, result);
  42416. result.a = 1 + 0.01 * saturation;
  42417. };
  42418. /**
  42419. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42420. * @param value The input slider value in range [-100,100].
  42421. * @returns Adjusted value.
  42422. */
  42423. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42424. value /= 100;
  42425. var x = Math.abs(value);
  42426. x = Math.pow(x, 2);
  42427. if (value < 0) {
  42428. x *= -1;
  42429. }
  42430. x *= 100;
  42431. return x;
  42432. };
  42433. /**
  42434. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42435. * @param hue The hue (H) input.
  42436. * @param saturation The saturation (S) input.
  42437. * @param brightness The brightness (B) input.
  42438. * @result An RGBA color represented as Vector4.
  42439. */
  42440. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42441. var h = ColorCurves.clamp(hue, 0, 360);
  42442. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42443. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42444. if (s === 0) {
  42445. result.r = v;
  42446. result.g = v;
  42447. result.b = v;
  42448. }
  42449. else {
  42450. // sector 0 to 5
  42451. h /= 60;
  42452. var i = Math.floor(h);
  42453. // fractional part of h
  42454. var f = h - i;
  42455. var p = v * (1 - s);
  42456. var q = v * (1 - s * f);
  42457. var t = v * (1 - s * (1 - f));
  42458. switch (i) {
  42459. case 0:
  42460. result.r = v;
  42461. result.g = t;
  42462. result.b = p;
  42463. break;
  42464. case 1:
  42465. result.r = q;
  42466. result.g = v;
  42467. result.b = p;
  42468. break;
  42469. case 2:
  42470. result.r = p;
  42471. result.g = v;
  42472. result.b = t;
  42473. break;
  42474. case 3:
  42475. result.r = p;
  42476. result.g = q;
  42477. result.b = v;
  42478. break;
  42479. case 4:
  42480. result.r = t;
  42481. result.g = p;
  42482. result.b = v;
  42483. break;
  42484. default: // case 5:
  42485. result.r = v;
  42486. result.g = p;
  42487. result.b = q;
  42488. break;
  42489. }
  42490. }
  42491. result.a = 1;
  42492. };
  42493. /**
  42494. * Returns a value clamped between min and max
  42495. * @param value The value to clamp
  42496. * @param min The minimum of value
  42497. * @param max The maximum of value
  42498. * @returns The clamped value.
  42499. */
  42500. ColorCurves.clamp = function (value, min, max) {
  42501. return Math.min(Math.max(value, min), max);
  42502. };
  42503. /**
  42504. * Clones the current color curve instance.
  42505. * @return The cloned curves
  42506. */
  42507. ColorCurves.prototype.clone = function () {
  42508. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42509. };
  42510. /**
  42511. * Serializes the current color curve instance to a json representation.
  42512. * @return a JSON representation
  42513. */
  42514. ColorCurves.prototype.serialize = function () {
  42515. return BABYLON.SerializationHelper.Serialize(this);
  42516. };
  42517. /**
  42518. * Parses the color curve from a json representation.
  42519. * @param source the JSON source to parse
  42520. * @return The parsed curves
  42521. */
  42522. ColorCurves.Parse = function (source) {
  42523. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42524. };
  42525. __decorate([
  42526. BABYLON.serialize()
  42527. ], ColorCurves.prototype, "_globalHue", void 0);
  42528. __decorate([
  42529. BABYLON.serialize()
  42530. ], ColorCurves.prototype, "_globalDensity", void 0);
  42531. __decorate([
  42532. BABYLON.serialize()
  42533. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42534. __decorate([
  42535. BABYLON.serialize()
  42536. ], ColorCurves.prototype, "_globalExposure", void 0);
  42537. __decorate([
  42538. BABYLON.serialize()
  42539. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42540. __decorate([
  42541. BABYLON.serialize()
  42542. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42543. __decorate([
  42544. BABYLON.serialize()
  42545. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42546. __decorate([
  42547. BABYLON.serialize()
  42548. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42549. __decorate([
  42550. BABYLON.serialize()
  42551. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42552. __decorate([
  42553. BABYLON.serialize()
  42554. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42555. __decorate([
  42556. BABYLON.serialize()
  42557. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42558. __decorate([
  42559. BABYLON.serialize()
  42560. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42561. return ColorCurves;
  42562. }());
  42563. BABYLON.ColorCurves = ColorCurves;
  42564. })(BABYLON || (BABYLON = {}));
  42565. //# sourceMappingURL=babylon.colorCurves.js.map
  42566. //# sourceMappingURL=babylon.behavior.js.map
  42567. var BABYLON;
  42568. (function (BABYLON) {
  42569. /**
  42570. * "Static Class" containing the most commonly used helper while dealing with material for
  42571. * rendering purpose.
  42572. *
  42573. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42574. *
  42575. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42576. */
  42577. var MaterialHelper = /** @class */ (function () {
  42578. function MaterialHelper() {
  42579. }
  42580. /**
  42581. * Bind the current view position to an effect.
  42582. * @param effect The effect to be bound
  42583. * @param scene The scene the eyes position is used from
  42584. */
  42585. MaterialHelper.BindEyePosition = function (effect, scene) {
  42586. if (scene._forcedViewPosition) {
  42587. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42588. return;
  42589. }
  42590. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42591. };
  42592. /**
  42593. * Helps preparing the defines values about the UVs in used in the effect.
  42594. * UVs are shared as much as we can accross chanels in the shaders.
  42595. * @param texture The texture we are preparing the UVs for
  42596. * @param defines The defines to update
  42597. * @param key The chanel key "diffuse", "specular"... used in the shader
  42598. */
  42599. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42600. defines._needUVs = true;
  42601. defines[key] = true;
  42602. if (texture.getTextureMatrix().isIdentity(true)) {
  42603. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42604. if (texture.coordinatesIndex === 0) {
  42605. defines["MAINUV1"] = true;
  42606. }
  42607. else {
  42608. defines["MAINUV2"] = true;
  42609. }
  42610. }
  42611. else {
  42612. defines[key + "DIRECTUV"] = 0;
  42613. }
  42614. };
  42615. /**
  42616. * Binds a texture matrix value to its corrsponding uniform
  42617. * @param texture The texture to bind the matrix for
  42618. * @param uniformBuffer The uniform buffer receivin the data
  42619. * @param key The chanel key "diffuse", "specular"... used in the shader
  42620. */
  42621. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42622. var matrix = texture.getTextureMatrix();
  42623. if (!matrix.isIdentity(true)) {
  42624. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42625. }
  42626. };
  42627. /**
  42628. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42629. * @param mesh defines the current mesh
  42630. * @param scene defines the current scene
  42631. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42632. * @param pointsCloud defines if point cloud rendering has to be turned on
  42633. * @param fogEnabled defines if fog has to be turned on
  42634. * @param alphaTest defines if alpha testing has to be turned on
  42635. * @param defines defines the current list of defines
  42636. */
  42637. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42638. if (defines._areMiscDirty) {
  42639. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42640. defines["POINTSIZE"] = pointsCloud;
  42641. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42642. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42643. defines["ALPHATEST"] = alphaTest;
  42644. }
  42645. };
  42646. /**
  42647. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42648. * @param scene defines the current scene
  42649. * @param engine defines the current engine
  42650. * @param defines specifies the list of active defines
  42651. * @param useInstances defines if instances have to be turned on
  42652. * @param useClipPlane defines if clip plane have to be turned on
  42653. */
  42654. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42655. if (useClipPlane === void 0) { useClipPlane = null; }
  42656. var changed = false;
  42657. if (useClipPlane == null) {
  42658. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42659. }
  42660. if (defines["CLIPPLANE"] !== useClipPlane) {
  42661. defines["CLIPPLANE"] = useClipPlane;
  42662. changed = true;
  42663. }
  42664. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42665. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42666. changed = true;
  42667. }
  42668. if (defines["INSTANCES"] !== useInstances) {
  42669. defines["INSTANCES"] = useInstances;
  42670. changed = true;
  42671. }
  42672. if (changed) {
  42673. defines.markAsUnprocessed();
  42674. }
  42675. };
  42676. /**
  42677. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42678. * @param mesh The mesh containing the geometry data we will draw
  42679. * @param defines The defines to update
  42680. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42681. * @param useBones Precise whether bones should be used or not (override mesh info)
  42682. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42683. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42684. * @returns false if defines are considered not dirty and have not been checked
  42685. */
  42686. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42687. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42688. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42689. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42690. return false;
  42691. }
  42692. defines._normals = defines._needNormals;
  42693. defines._uvs = defines._needUVs;
  42694. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42695. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42696. defines["TANGENT"] = true;
  42697. }
  42698. if (defines._needUVs) {
  42699. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42700. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42701. }
  42702. else {
  42703. defines["UV1"] = false;
  42704. defines["UV2"] = false;
  42705. }
  42706. if (useVertexColor) {
  42707. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42708. defines["VERTEXCOLOR"] = hasVertexColors;
  42709. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42710. }
  42711. if (useBones) {
  42712. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42713. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42714. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42715. }
  42716. else {
  42717. defines["NUM_BONE_INFLUENCERS"] = 0;
  42718. defines["BonesPerMesh"] = 0;
  42719. }
  42720. }
  42721. if (useMorphTargets) {
  42722. var manager = mesh.morphTargetManager;
  42723. if (manager) {
  42724. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42725. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42726. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42727. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42728. }
  42729. else {
  42730. defines["MORPHTARGETS_TANGENT"] = false;
  42731. defines["MORPHTARGETS_NORMAL"] = false;
  42732. defines["MORPHTARGETS"] = false;
  42733. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42734. }
  42735. }
  42736. return true;
  42737. };
  42738. /**
  42739. * Prepares the defines related to the light information passed in parameter
  42740. * @param scene The scene we are intending to draw
  42741. * @param mesh The mesh the effect is compiling for
  42742. * @param defines The defines to update
  42743. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42744. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42745. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42746. * @returns true if normals will be required for the rest of the effect
  42747. */
  42748. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42749. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42750. if (disableLighting === void 0) { disableLighting = false; }
  42751. if (!defines._areLightsDirty) {
  42752. return defines._needNormals;
  42753. }
  42754. var lightIndex = 0;
  42755. var needNormals = false;
  42756. var needRebuild = false;
  42757. var lightmapMode = false;
  42758. var shadowEnabled = false;
  42759. var specularEnabled = false;
  42760. if (scene.lightsEnabled && !disableLighting) {
  42761. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42762. var light = _a[_i];
  42763. needNormals = true;
  42764. if (defines["LIGHT" + lightIndex] === undefined) {
  42765. needRebuild = true;
  42766. }
  42767. defines["LIGHT" + lightIndex] = true;
  42768. defines["SPOTLIGHT" + lightIndex] = false;
  42769. defines["HEMILIGHT" + lightIndex] = false;
  42770. defines["POINTLIGHT" + lightIndex] = false;
  42771. defines["DIRLIGHT" + lightIndex] = false;
  42772. var type;
  42773. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42774. type = "SPOTLIGHT" + lightIndex;
  42775. var spotLight = light;
  42776. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42777. }
  42778. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42779. type = "HEMILIGHT" + lightIndex;
  42780. }
  42781. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42782. type = "POINTLIGHT" + lightIndex;
  42783. }
  42784. else {
  42785. type = "DIRLIGHT" + lightIndex;
  42786. }
  42787. defines[type] = true;
  42788. // Specular
  42789. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42790. specularEnabled = true;
  42791. }
  42792. // Shadows
  42793. defines["SHADOW" + lightIndex] = false;
  42794. defines["SHADOWPCF" + lightIndex] = false;
  42795. defines["SHADOWPCSS" + lightIndex] = false;
  42796. defines["SHADOWPOISSON" + lightIndex] = false;
  42797. defines["SHADOWESM" + lightIndex] = false;
  42798. defines["SHADOWCUBE" + lightIndex] = false;
  42799. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42800. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42801. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42802. var shadowGenerator = light.getShadowGenerator();
  42803. if (shadowGenerator) {
  42804. shadowEnabled = true;
  42805. shadowGenerator.prepareDefines(defines, lightIndex);
  42806. }
  42807. }
  42808. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42809. lightmapMode = true;
  42810. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42811. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42812. }
  42813. else {
  42814. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42815. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42816. }
  42817. lightIndex++;
  42818. if (lightIndex === maxSimultaneousLights)
  42819. break;
  42820. }
  42821. }
  42822. defines["SPECULARTERM"] = specularEnabled;
  42823. defines["SHADOWS"] = shadowEnabled;
  42824. // Resetting all other lights if any
  42825. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42826. if (defines["LIGHT" + index] !== undefined) {
  42827. defines["LIGHT" + index] = false;
  42828. defines["HEMILIGHT" + lightIndex] = false;
  42829. defines["POINTLIGHT" + lightIndex] = false;
  42830. defines["DIRLIGHT" + lightIndex] = false;
  42831. defines["SPOTLIGHT" + lightIndex] = false;
  42832. defines["SHADOW" + lightIndex] = false;
  42833. }
  42834. }
  42835. var caps = scene.getEngine().getCaps();
  42836. if (defines["SHADOWFLOAT"] === undefined) {
  42837. needRebuild = true;
  42838. }
  42839. defines["SHADOWFLOAT"] = shadowEnabled &&
  42840. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42841. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42842. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42843. if (needRebuild) {
  42844. defines.rebuild();
  42845. }
  42846. return needNormals;
  42847. };
  42848. /**
  42849. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42850. * that won t be acctive due to defines being turned off.
  42851. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42852. * @param samplersList The samplers list
  42853. * @param defines The defines helping in the list generation
  42854. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42855. */
  42856. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42857. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42858. var uniformsList;
  42859. var uniformBuffersList = null;
  42860. if (uniformsListOrOptions.uniformsNames) {
  42861. var options = uniformsListOrOptions;
  42862. uniformsList = options.uniformsNames;
  42863. uniformBuffersList = options.uniformBuffersNames;
  42864. samplersList = options.samplers;
  42865. defines = options.defines;
  42866. maxSimultaneousLights = options.maxSimultaneousLights;
  42867. }
  42868. else {
  42869. uniformsList = uniformsListOrOptions;
  42870. if (!samplersList) {
  42871. samplersList = [];
  42872. }
  42873. }
  42874. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42875. if (!defines["LIGHT" + lightIndex]) {
  42876. break;
  42877. }
  42878. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42879. if (uniformBuffersList) {
  42880. uniformBuffersList.push("Light" + lightIndex);
  42881. }
  42882. samplersList.push("shadowSampler" + lightIndex);
  42883. samplersList.push("depthSampler" + lightIndex);
  42884. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42885. samplersList.push("projectionLightSampler" + lightIndex);
  42886. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42887. }
  42888. }
  42889. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42890. uniformsList.push("morphTargetInfluences");
  42891. }
  42892. };
  42893. /**
  42894. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42895. * @param defines The defines to update while falling back
  42896. * @param fallbacks The authorized effect fallbacks
  42897. * @param maxSimultaneousLights The maximum number of lights allowed
  42898. * @param rank the current rank of the Effect
  42899. * @returns The newly affected rank
  42900. */
  42901. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42902. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42903. if (rank === void 0) { rank = 0; }
  42904. var lightFallbackRank = 0;
  42905. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42906. if (!defines["LIGHT" + lightIndex]) {
  42907. break;
  42908. }
  42909. if (lightIndex > 0) {
  42910. lightFallbackRank = rank + lightIndex;
  42911. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42912. }
  42913. if (!defines["SHADOWS"]) {
  42914. if (defines["SHADOW" + lightIndex]) {
  42915. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42916. }
  42917. if (defines["SHADOWPCF" + lightIndex]) {
  42918. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42919. }
  42920. if (defines["SHADOWPCSS" + lightIndex]) {
  42921. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42922. }
  42923. if (defines["SHADOWPOISSON" + lightIndex]) {
  42924. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42925. }
  42926. if (defines["SHADOWESM" + lightIndex]) {
  42927. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42928. }
  42929. }
  42930. }
  42931. return lightFallbackRank++;
  42932. };
  42933. /**
  42934. * Prepares the list of attributes required for morph targets according to the effect defines.
  42935. * @param attribs The current list of supported attribs
  42936. * @param mesh The mesh to prepare the morph targets attributes for
  42937. * @param defines The current Defines of the effect
  42938. */
  42939. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42940. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42941. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42942. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42943. var manager = mesh.morphTargetManager;
  42944. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42945. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42946. for (var index = 0; index < influencers; index++) {
  42947. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42948. if (normal) {
  42949. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42950. }
  42951. if (tangent) {
  42952. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42953. }
  42954. if (attribs.length > maxAttributesCount) {
  42955. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42956. }
  42957. }
  42958. }
  42959. };
  42960. /**
  42961. * Prepares the list of attributes required for bones according to the effect defines.
  42962. * @param attribs The current list of supported attribs
  42963. * @param mesh The mesh to prepare the bones attributes for
  42964. * @param defines The current Defines of the effect
  42965. * @param fallbacks The current efffect fallback strategy
  42966. */
  42967. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42968. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42969. fallbacks.addCPUSkinningFallback(0, mesh);
  42970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42972. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42973. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42974. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42975. }
  42976. }
  42977. };
  42978. /**
  42979. * Prepares the list of attributes required for instances according to the effect defines.
  42980. * @param attribs The current list of supported attribs
  42981. * @param defines The current Defines of the effect
  42982. */
  42983. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42984. if (defines["INSTANCES"]) {
  42985. attribs.push("world0");
  42986. attribs.push("world1");
  42987. attribs.push("world2");
  42988. attribs.push("world3");
  42989. }
  42990. };
  42991. /**
  42992. * Binds the light shadow information to the effect for the given mesh.
  42993. * @param light The light containing the generator
  42994. * @param scene The scene the lights belongs to
  42995. * @param mesh The mesh we are binding the information to render
  42996. * @param lightIndex The light index in the effect used to render the mesh
  42997. * @param effect The effect we are binding the data to
  42998. */
  42999. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  43000. if (light.shadowEnabled && mesh.receiveShadows) {
  43001. var shadowGenerator = light.getShadowGenerator();
  43002. if (shadowGenerator) {
  43003. shadowGenerator.bindShadowLight(lightIndex, effect);
  43004. }
  43005. }
  43006. };
  43007. /**
  43008. * Binds the light information to the effect.
  43009. * @param light The light containing the generator
  43010. * @param effect The effect we are binding the data to
  43011. * @param lightIndex The light index in the effect used to render
  43012. */
  43013. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43014. light.transferToEffect(effect, lightIndex + "");
  43015. };
  43016. /**
  43017. * Binds the lights information from the scene to the effect for the given mesh.
  43018. * @param scene The scene the lights belongs to
  43019. * @param mesh The mesh we are binding the information to render
  43020. * @param effect The effect we are binding the data to
  43021. * @param defines The generated defines for the effect
  43022. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43023. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43024. */
  43025. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43026. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43027. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43028. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43029. for (var i = 0; i < len; i++) {
  43030. var light = mesh._lightSources[i];
  43031. var iAsString = i.toString();
  43032. var scaledIntensity = light.getScaledIntensity();
  43033. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43034. MaterialHelper.BindLightProperties(light, effect, i);
  43035. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43036. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43037. if (defines["SPECULARTERM"]) {
  43038. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43039. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43040. }
  43041. // Shadows
  43042. if (scene.shadowsEnabled) {
  43043. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43044. }
  43045. light._uniformBuffer.update();
  43046. }
  43047. };
  43048. /**
  43049. * Binds the fog information from the scene to the effect for the given mesh.
  43050. * @param scene The scene the lights belongs to
  43051. * @param mesh The mesh we are binding the information to render
  43052. * @param effect The effect we are binding the data to
  43053. */
  43054. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  43055. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43056. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43057. effect.setColor3("vFogColor", scene.fogColor);
  43058. }
  43059. };
  43060. /**
  43061. * Binds the bones information from the mesh to the effect.
  43062. * @param mesh The mesh we are binding the information to render
  43063. * @param effect The effect we are binding the data to
  43064. */
  43065. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43066. if (!effect || !mesh) {
  43067. return;
  43068. }
  43069. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43070. mesh.computeBonesUsingShaders = false;
  43071. }
  43072. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43073. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  43074. if (matrices) {
  43075. effect.setMatrices("mBones", matrices);
  43076. }
  43077. }
  43078. };
  43079. /**
  43080. * Binds the morph targets information from the mesh to the effect.
  43081. * @param abstractMesh The mesh we are binding the information to render
  43082. * @param effect The effect we are binding the data to
  43083. */
  43084. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43085. var manager = abstractMesh.morphTargetManager;
  43086. if (!abstractMesh || !manager) {
  43087. return;
  43088. }
  43089. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43090. };
  43091. /**
  43092. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43093. * @param defines The generated defines used in the effect
  43094. * @param effect The effect we are binding the data to
  43095. * @param scene The scene we are willing to render with logarithmic scale for
  43096. */
  43097. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43098. if (defines["LOGARITHMICDEPTH"]) {
  43099. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43100. }
  43101. };
  43102. /**
  43103. * Binds the clip plane information from the scene to the effect.
  43104. * @param scene The scene the clip plane information are extracted from
  43105. * @param effect The effect we are binding the data to
  43106. */
  43107. MaterialHelper.BindClipPlane = function (effect, scene) {
  43108. if (scene.clipPlane) {
  43109. var clipPlane = scene.clipPlane;
  43110. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43111. }
  43112. };
  43113. return MaterialHelper;
  43114. }());
  43115. BABYLON.MaterialHelper = MaterialHelper;
  43116. })(BABYLON || (BABYLON = {}));
  43117. //# sourceMappingURL=babylon.materialHelper.js.map
  43118. var BABYLON;
  43119. (function (BABYLON) {
  43120. var PushMaterial = /** @class */ (function (_super) {
  43121. __extends(PushMaterial, _super);
  43122. function PushMaterial(name, scene) {
  43123. var _this = _super.call(this, name, scene) || this;
  43124. _this._normalMatrix = new BABYLON.Matrix();
  43125. _this.storeEffectOnSubMeshes = true;
  43126. return _this;
  43127. }
  43128. PushMaterial.prototype.getEffect = function () {
  43129. return this._activeEffect;
  43130. };
  43131. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43132. if (!mesh) {
  43133. return false;
  43134. }
  43135. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43136. return true;
  43137. }
  43138. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43139. };
  43140. /**
  43141. * Binds the given world matrix to the active effect
  43142. *
  43143. * @param world the matrix to bind
  43144. */
  43145. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43146. this._activeEffect.setMatrix("world", world);
  43147. };
  43148. /**
  43149. * Binds the given normal matrix to the active effect
  43150. *
  43151. * @param normalMatrix the matrix to bind
  43152. */
  43153. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43154. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43155. };
  43156. PushMaterial.prototype.bind = function (world, mesh) {
  43157. if (!mesh) {
  43158. return;
  43159. }
  43160. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43161. };
  43162. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43163. if (effect === void 0) { effect = null; }
  43164. _super.prototype._afterBind.call(this, mesh);
  43165. this.getScene()._cachedEffect = effect;
  43166. };
  43167. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43168. if (visibility === void 0) { visibility = 1; }
  43169. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43170. };
  43171. return PushMaterial;
  43172. }(BABYLON.Material));
  43173. BABYLON.PushMaterial = PushMaterial;
  43174. })(BABYLON || (BABYLON = {}));
  43175. //# sourceMappingURL=babylon.pushMaterial.js.map
  43176. var BABYLON;
  43177. (function (BABYLON) {
  43178. /** @hidden */
  43179. var StandardMaterialDefines = /** @class */ (function (_super) {
  43180. __extends(StandardMaterialDefines, _super);
  43181. function StandardMaterialDefines() {
  43182. var _this = _super.call(this) || this;
  43183. _this.MAINUV1 = false;
  43184. _this.MAINUV2 = false;
  43185. _this.DIFFUSE = false;
  43186. _this.DIFFUSEDIRECTUV = 0;
  43187. _this.AMBIENT = false;
  43188. _this.AMBIENTDIRECTUV = 0;
  43189. _this.OPACITY = false;
  43190. _this.OPACITYDIRECTUV = 0;
  43191. _this.OPACITYRGB = false;
  43192. _this.REFLECTION = false;
  43193. _this.EMISSIVE = false;
  43194. _this.EMISSIVEDIRECTUV = 0;
  43195. _this.SPECULAR = false;
  43196. _this.SPECULARDIRECTUV = 0;
  43197. _this.BUMP = false;
  43198. _this.BUMPDIRECTUV = 0;
  43199. _this.PARALLAX = false;
  43200. _this.PARALLAXOCCLUSION = false;
  43201. _this.SPECULAROVERALPHA = false;
  43202. _this.CLIPPLANE = false;
  43203. _this.ALPHATEST = false;
  43204. _this.DEPTHPREPASS = false;
  43205. _this.ALPHAFROMDIFFUSE = false;
  43206. _this.POINTSIZE = false;
  43207. _this.FOG = false;
  43208. _this.SPECULARTERM = false;
  43209. _this.DIFFUSEFRESNEL = false;
  43210. _this.OPACITYFRESNEL = false;
  43211. _this.REFLECTIONFRESNEL = false;
  43212. _this.REFRACTIONFRESNEL = false;
  43213. _this.EMISSIVEFRESNEL = false;
  43214. _this.FRESNEL = false;
  43215. _this.NORMAL = false;
  43216. _this.UV1 = false;
  43217. _this.UV2 = false;
  43218. _this.VERTEXCOLOR = false;
  43219. _this.VERTEXALPHA = false;
  43220. _this.NUM_BONE_INFLUENCERS = 0;
  43221. _this.BonesPerMesh = 0;
  43222. _this.INSTANCES = false;
  43223. _this.GLOSSINESS = false;
  43224. _this.ROUGHNESS = false;
  43225. _this.EMISSIVEASILLUMINATION = false;
  43226. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43227. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43228. _this.LIGHTMAP = false;
  43229. _this.LIGHTMAPDIRECTUV = 0;
  43230. _this.OBJECTSPACE_NORMALMAP = false;
  43231. _this.USELIGHTMAPASSHADOWMAP = false;
  43232. _this.REFLECTIONMAP_3D = false;
  43233. _this.REFLECTIONMAP_SPHERICAL = false;
  43234. _this.REFLECTIONMAP_PLANAR = false;
  43235. _this.REFLECTIONMAP_CUBIC = false;
  43236. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43237. _this.REFLECTIONMAP_PROJECTION = false;
  43238. _this.REFLECTIONMAP_SKYBOX = false;
  43239. _this.REFLECTIONMAP_EXPLICIT = false;
  43240. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43241. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43242. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43243. _this.INVERTCUBICMAP = false;
  43244. _this.LOGARITHMICDEPTH = false;
  43245. _this.REFRACTION = false;
  43246. _this.REFRACTIONMAP_3D = false;
  43247. _this.REFLECTIONOVERALPHA = false;
  43248. _this.TWOSIDEDLIGHTING = false;
  43249. _this.SHADOWFLOAT = false;
  43250. _this.MORPHTARGETS = false;
  43251. _this.MORPHTARGETS_NORMAL = false;
  43252. _this.MORPHTARGETS_TANGENT = false;
  43253. _this.NUM_MORPH_INFLUENCERS = 0;
  43254. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43255. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43256. _this.IMAGEPROCESSING = false;
  43257. _this.VIGNETTE = false;
  43258. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43259. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43260. _this.TONEMAPPING = false;
  43261. _this.CONTRAST = false;
  43262. _this.COLORCURVES = false;
  43263. _this.COLORGRADING = false;
  43264. _this.COLORGRADING3D = false;
  43265. _this.SAMPLER3DGREENDEPTH = false;
  43266. _this.SAMPLER3DBGRMAP = false;
  43267. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43268. /**
  43269. * If the reflection texture on this material is in linear color space
  43270. * @hidden
  43271. */
  43272. _this.IS_REFLECTION_LINEAR = false;
  43273. /**
  43274. * If the refraction texture on this material is in linear color space
  43275. * @hidden
  43276. */
  43277. _this.IS_REFRACTION_LINEAR = false;
  43278. _this.EXPOSURE = false;
  43279. _this.rebuild();
  43280. return _this;
  43281. }
  43282. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43283. var modes = [
  43284. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43285. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43286. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43287. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43288. ];
  43289. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43290. var mode = modes_1[_i];
  43291. this[mode] = (mode === modeToEnable);
  43292. }
  43293. };
  43294. return StandardMaterialDefines;
  43295. }(BABYLON.MaterialDefines));
  43296. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43297. var StandardMaterial = /** @class */ (function (_super) {
  43298. __extends(StandardMaterial, _super);
  43299. function StandardMaterial(name, scene) {
  43300. var _this = _super.call(this, name, scene) || this;
  43301. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43302. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43303. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43304. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43305. _this.specularPower = 64;
  43306. _this._useAlphaFromDiffuseTexture = false;
  43307. _this._useEmissiveAsIllumination = false;
  43308. _this._linkEmissiveWithDiffuse = false;
  43309. _this._useSpecularOverAlpha = false;
  43310. _this._useReflectionOverAlpha = false;
  43311. _this._disableLighting = false;
  43312. _this._useObjectSpaceNormalMap = false;
  43313. _this._useParallax = false;
  43314. _this._useParallaxOcclusion = false;
  43315. _this.parallaxScaleBias = 0.05;
  43316. _this._roughness = 0;
  43317. _this.indexOfRefraction = 0.98;
  43318. _this.invertRefractionY = true;
  43319. /**
  43320. * Defines the alpha limits in alpha test mode
  43321. */
  43322. _this.alphaCutOff = 0.4;
  43323. _this._useLightmapAsShadowmap = false;
  43324. _this._useReflectionFresnelFromSpecular = false;
  43325. _this._useGlossinessFromSpecularMapAlpha = false;
  43326. _this._maxSimultaneousLights = 4;
  43327. /**
  43328. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43329. */
  43330. _this._invertNormalMapX = false;
  43331. /**
  43332. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43333. */
  43334. _this._invertNormalMapY = false;
  43335. /**
  43336. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43337. */
  43338. _this._twoSidedLighting = false;
  43339. _this._renderTargets = new BABYLON.SmartArray(16);
  43340. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43341. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43342. // Setup the default processing configuration to the scene.
  43343. _this._attachImageProcessingConfiguration(null);
  43344. _this.getRenderTargetTextures = function () {
  43345. _this._renderTargets.reset();
  43346. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43347. _this._renderTargets.push(_this._reflectionTexture);
  43348. }
  43349. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43350. _this._renderTargets.push(_this._refractionTexture);
  43351. }
  43352. return _this._renderTargets;
  43353. };
  43354. return _this;
  43355. }
  43356. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43357. /**
  43358. * Gets the image processing configuration used either in this material.
  43359. */
  43360. get: function () {
  43361. return this._imageProcessingConfiguration;
  43362. },
  43363. /**
  43364. * Sets the Default image processing configuration used either in the this material.
  43365. *
  43366. * If sets to null, the scene one is in use.
  43367. */
  43368. set: function (value) {
  43369. this._attachImageProcessingConfiguration(value);
  43370. // Ensure the effect will be rebuilt.
  43371. this._markAllSubMeshesAsTexturesDirty();
  43372. },
  43373. enumerable: true,
  43374. configurable: true
  43375. });
  43376. /**
  43377. * Attaches a new image processing configuration to the Standard Material.
  43378. * @param configuration
  43379. */
  43380. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43381. var _this = this;
  43382. if (configuration === this._imageProcessingConfiguration) {
  43383. return;
  43384. }
  43385. // Detaches observer.
  43386. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43387. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43388. }
  43389. // Pick the scene configuration if needed.
  43390. if (!configuration) {
  43391. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43392. }
  43393. else {
  43394. this._imageProcessingConfiguration = configuration;
  43395. }
  43396. // Attaches observer.
  43397. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43398. _this._markAllSubMeshesAsImageProcessingDirty();
  43399. });
  43400. };
  43401. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43402. /**
  43403. * Gets wether the color curves effect is enabled.
  43404. */
  43405. get: function () {
  43406. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43407. },
  43408. /**
  43409. * Sets wether the color curves effect is enabled.
  43410. */
  43411. set: function (value) {
  43412. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43413. },
  43414. enumerable: true,
  43415. configurable: true
  43416. });
  43417. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43418. /**
  43419. * Gets wether the color grading effect is enabled.
  43420. */
  43421. get: function () {
  43422. return this.imageProcessingConfiguration.colorGradingEnabled;
  43423. },
  43424. /**
  43425. * Gets wether the color grading effect is enabled.
  43426. */
  43427. set: function (value) {
  43428. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43429. },
  43430. enumerable: true,
  43431. configurable: true
  43432. });
  43433. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43434. /**
  43435. * Gets wether tonemapping is enabled or not.
  43436. */
  43437. get: function () {
  43438. return this._imageProcessingConfiguration.toneMappingEnabled;
  43439. },
  43440. /**
  43441. * Sets wether tonemapping is enabled or not
  43442. */
  43443. set: function (value) {
  43444. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43445. },
  43446. enumerable: true,
  43447. configurable: true
  43448. });
  43449. ;
  43450. ;
  43451. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43452. /**
  43453. * The camera exposure used on this material.
  43454. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43455. * This corresponds to a photographic exposure.
  43456. */
  43457. get: function () {
  43458. return this._imageProcessingConfiguration.exposure;
  43459. },
  43460. /**
  43461. * The camera exposure used on this material.
  43462. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43463. * This corresponds to a photographic exposure.
  43464. */
  43465. set: function (value) {
  43466. this._imageProcessingConfiguration.exposure = value;
  43467. },
  43468. enumerable: true,
  43469. configurable: true
  43470. });
  43471. ;
  43472. ;
  43473. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43474. /**
  43475. * Gets The camera contrast used on this material.
  43476. */
  43477. get: function () {
  43478. return this._imageProcessingConfiguration.contrast;
  43479. },
  43480. /**
  43481. * Sets The camera contrast used on this material.
  43482. */
  43483. set: function (value) {
  43484. this._imageProcessingConfiguration.contrast = value;
  43485. },
  43486. enumerable: true,
  43487. configurable: true
  43488. });
  43489. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43490. /**
  43491. * Gets the Color Grading 2D Lookup Texture.
  43492. */
  43493. get: function () {
  43494. return this._imageProcessingConfiguration.colorGradingTexture;
  43495. },
  43496. /**
  43497. * Sets the Color Grading 2D Lookup Texture.
  43498. */
  43499. set: function (value) {
  43500. this._imageProcessingConfiguration.colorGradingTexture = value;
  43501. },
  43502. enumerable: true,
  43503. configurable: true
  43504. });
  43505. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43506. /**
  43507. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43508. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43509. * 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;
  43510. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43511. */
  43512. get: function () {
  43513. return this._imageProcessingConfiguration.colorCurves;
  43514. },
  43515. /**
  43516. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43517. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43518. * 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;
  43519. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43520. */
  43521. set: function (value) {
  43522. this._imageProcessingConfiguration.colorCurves = value;
  43523. },
  43524. enumerable: true,
  43525. configurable: true
  43526. });
  43527. StandardMaterial.prototype.getClassName = function () {
  43528. return "StandardMaterial";
  43529. };
  43530. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43531. get: function () {
  43532. return this._useLogarithmicDepth;
  43533. },
  43534. set: function (value) {
  43535. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43536. this._markAllSubMeshesAsMiscDirty();
  43537. },
  43538. enumerable: true,
  43539. configurable: true
  43540. });
  43541. StandardMaterial.prototype.needAlphaBlending = function () {
  43542. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43543. };
  43544. StandardMaterial.prototype.needAlphaTesting = function () {
  43545. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43546. };
  43547. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43548. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43549. };
  43550. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43551. return this._diffuseTexture;
  43552. };
  43553. /**
  43554. * Child classes can use it to update shaders
  43555. */
  43556. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43557. if (useInstances === void 0) { useInstances = false; }
  43558. if (subMesh.effect && this.isFrozen) {
  43559. if (this._wasPreviouslyReady && subMesh.effect) {
  43560. return true;
  43561. }
  43562. }
  43563. if (!subMesh._materialDefines) {
  43564. subMesh._materialDefines = new StandardMaterialDefines();
  43565. }
  43566. var scene = this.getScene();
  43567. var defines = subMesh._materialDefines;
  43568. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43569. if (defines._renderId === scene.getRenderId()) {
  43570. return true;
  43571. }
  43572. }
  43573. var engine = scene.getEngine();
  43574. // Lights
  43575. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43576. // Textures
  43577. if (defines._areTexturesDirty) {
  43578. defines._needUVs = false;
  43579. defines.MAINUV1 = false;
  43580. defines.MAINUV2 = false;
  43581. if (scene.texturesEnabled) {
  43582. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43583. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43584. return false;
  43585. }
  43586. else {
  43587. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43588. }
  43589. }
  43590. else {
  43591. defines.DIFFUSE = false;
  43592. }
  43593. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43594. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43595. return false;
  43596. }
  43597. else {
  43598. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43599. }
  43600. }
  43601. else {
  43602. defines.AMBIENT = false;
  43603. }
  43604. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43605. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43606. return false;
  43607. }
  43608. else {
  43609. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43610. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43611. }
  43612. }
  43613. else {
  43614. defines.OPACITY = false;
  43615. }
  43616. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43617. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43618. return false;
  43619. }
  43620. else {
  43621. defines._needNormals = true;
  43622. defines.REFLECTION = true;
  43623. defines.ROUGHNESS = (this._roughness > 0);
  43624. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43625. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43626. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43627. switch (this._reflectionTexture.coordinatesMode) {
  43628. case BABYLON.Texture.EXPLICIT_MODE:
  43629. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43630. break;
  43631. case BABYLON.Texture.PLANAR_MODE:
  43632. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43633. break;
  43634. case BABYLON.Texture.PROJECTION_MODE:
  43635. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43636. break;
  43637. case BABYLON.Texture.SKYBOX_MODE:
  43638. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43639. break;
  43640. case BABYLON.Texture.SPHERICAL_MODE:
  43641. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43642. break;
  43643. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43644. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43645. break;
  43646. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43647. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43648. break;
  43649. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43650. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43651. break;
  43652. case BABYLON.Texture.CUBIC_MODE:
  43653. case BABYLON.Texture.INVCUBIC_MODE:
  43654. default:
  43655. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43656. break;
  43657. }
  43658. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43659. }
  43660. }
  43661. else {
  43662. defines.REFLECTION = false;
  43663. }
  43664. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43665. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43666. return false;
  43667. }
  43668. else {
  43669. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43670. }
  43671. }
  43672. else {
  43673. defines.EMISSIVE = false;
  43674. }
  43675. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43676. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43677. return false;
  43678. }
  43679. else {
  43680. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43681. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43682. }
  43683. }
  43684. else {
  43685. defines.LIGHTMAP = false;
  43686. }
  43687. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43688. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43689. return false;
  43690. }
  43691. else {
  43692. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43693. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43694. }
  43695. }
  43696. else {
  43697. defines.SPECULAR = false;
  43698. }
  43699. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43700. // Bump texure can not be not blocking.
  43701. if (!this._bumpTexture.isReady()) {
  43702. return false;
  43703. }
  43704. else {
  43705. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43706. defines.PARALLAX = this._useParallax;
  43707. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43708. }
  43709. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43710. }
  43711. else {
  43712. defines.BUMP = false;
  43713. }
  43714. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43715. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43716. return false;
  43717. }
  43718. else {
  43719. defines._needUVs = true;
  43720. defines.REFRACTION = true;
  43721. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43722. }
  43723. }
  43724. else {
  43725. defines.REFRACTION = false;
  43726. }
  43727. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43728. }
  43729. else {
  43730. defines.DIFFUSE = false;
  43731. defines.AMBIENT = false;
  43732. defines.OPACITY = false;
  43733. defines.REFLECTION = false;
  43734. defines.EMISSIVE = false;
  43735. defines.LIGHTMAP = false;
  43736. defines.BUMP = false;
  43737. defines.REFRACTION = false;
  43738. }
  43739. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43740. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43741. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43742. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43743. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43744. }
  43745. if (defines._areImageProcessingDirty) {
  43746. if (!this._imageProcessingConfiguration.isReady()) {
  43747. return false;
  43748. }
  43749. this._imageProcessingConfiguration.prepareDefines(defines);
  43750. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43751. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43752. }
  43753. if (defines._areFresnelDirty) {
  43754. if (StandardMaterial.FresnelEnabled) {
  43755. // Fresnel
  43756. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43757. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43758. this._reflectionFresnelParameters) {
  43759. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43760. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43761. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43762. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43763. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43764. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43765. defines._needNormals = true;
  43766. defines.FRESNEL = true;
  43767. }
  43768. }
  43769. else {
  43770. defines.FRESNEL = false;
  43771. }
  43772. }
  43773. // Misc.
  43774. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43775. // Attribs
  43776. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43777. // Values that need to be evaluated on every frame
  43778. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43779. // Get correct effect
  43780. if (defines.isDirty) {
  43781. defines.markAsProcessed();
  43782. scene.resetCachedMaterial();
  43783. // Fallbacks
  43784. var fallbacks = new BABYLON.EffectFallbacks();
  43785. if (defines.REFLECTION) {
  43786. fallbacks.addFallback(0, "REFLECTION");
  43787. }
  43788. if (defines.SPECULAR) {
  43789. fallbacks.addFallback(0, "SPECULAR");
  43790. }
  43791. if (defines.BUMP) {
  43792. fallbacks.addFallback(0, "BUMP");
  43793. }
  43794. if (defines.PARALLAX) {
  43795. fallbacks.addFallback(1, "PARALLAX");
  43796. }
  43797. if (defines.PARALLAXOCCLUSION) {
  43798. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43799. }
  43800. if (defines.SPECULAROVERALPHA) {
  43801. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43802. }
  43803. if (defines.FOG) {
  43804. fallbacks.addFallback(1, "FOG");
  43805. }
  43806. if (defines.POINTSIZE) {
  43807. fallbacks.addFallback(0, "POINTSIZE");
  43808. }
  43809. if (defines.LOGARITHMICDEPTH) {
  43810. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43811. }
  43812. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43813. if (defines.SPECULARTERM) {
  43814. fallbacks.addFallback(0, "SPECULARTERM");
  43815. }
  43816. if (defines.DIFFUSEFRESNEL) {
  43817. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43818. }
  43819. if (defines.OPACITYFRESNEL) {
  43820. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43821. }
  43822. if (defines.REFLECTIONFRESNEL) {
  43823. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43824. }
  43825. if (defines.EMISSIVEFRESNEL) {
  43826. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43827. }
  43828. if (defines.FRESNEL) {
  43829. fallbacks.addFallback(4, "FRESNEL");
  43830. }
  43831. //Attributes
  43832. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43833. if (defines.NORMAL) {
  43834. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43835. }
  43836. if (defines.UV1) {
  43837. attribs.push(BABYLON.VertexBuffer.UVKind);
  43838. }
  43839. if (defines.UV2) {
  43840. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43841. }
  43842. if (defines.VERTEXCOLOR) {
  43843. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43844. }
  43845. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43846. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43847. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43848. var shaderName = "default";
  43849. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43850. "vFogInfos", "vFogColor", "pointSize",
  43851. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43852. "mBones",
  43853. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43854. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43855. "vReflectionPosition", "vReflectionSize",
  43856. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43857. ];
  43858. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43859. var uniformBuffers = ["Material", "Scene"];
  43860. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43861. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43862. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43863. uniformsNames: uniforms,
  43864. uniformBuffersNames: uniformBuffers,
  43865. samplers: samplers,
  43866. defines: defines,
  43867. maxSimultaneousLights: this._maxSimultaneousLights
  43868. });
  43869. if (this.customShaderNameResolve) {
  43870. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43871. }
  43872. var join = defines.toString();
  43873. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43874. attributes: attribs,
  43875. uniformsNames: uniforms,
  43876. uniformBuffersNames: uniformBuffers,
  43877. samplers: samplers,
  43878. defines: join,
  43879. fallbacks: fallbacks,
  43880. onCompiled: this.onCompiled,
  43881. onError: this.onError,
  43882. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43883. }, engine), defines);
  43884. this.buildUniformLayout();
  43885. }
  43886. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43887. return false;
  43888. }
  43889. defines._renderId = scene.getRenderId();
  43890. this._wasPreviouslyReady = true;
  43891. return true;
  43892. };
  43893. StandardMaterial.prototype.buildUniformLayout = function () {
  43894. // Order is important !
  43895. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43896. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43897. this._uniformBuffer.addUniform("opacityParts", 4);
  43898. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43899. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43900. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43901. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43902. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43903. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43904. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43905. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43906. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43907. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43908. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43909. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43910. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43911. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43912. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43913. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43914. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43915. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43916. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43917. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43918. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43919. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43920. this._uniformBuffer.addUniform("specularMatrix", 16);
  43921. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43922. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43923. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43924. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43925. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43926. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43927. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43928. this._uniformBuffer.addUniform("pointSize", 1);
  43929. this._uniformBuffer.create();
  43930. };
  43931. StandardMaterial.prototype.unbind = function () {
  43932. if (this._activeEffect) {
  43933. var needFlag = false;
  43934. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43935. this._activeEffect.setTexture("reflection2DSampler", null);
  43936. needFlag = true;
  43937. }
  43938. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43939. this._activeEffect.setTexture("refraction2DSampler", null);
  43940. needFlag = true;
  43941. }
  43942. if (needFlag) {
  43943. this._markAllSubMeshesAsTexturesDirty();
  43944. }
  43945. }
  43946. _super.prototype.unbind.call(this);
  43947. };
  43948. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43949. var scene = this.getScene();
  43950. var defines = subMesh._materialDefines;
  43951. if (!defines) {
  43952. return;
  43953. }
  43954. var effect = subMesh.effect;
  43955. if (!effect) {
  43956. return;
  43957. }
  43958. this._activeEffect = effect;
  43959. // Matrices
  43960. this.bindOnlyWorldMatrix(world);
  43961. // Normal Matrix
  43962. if (defines.OBJECTSPACE_NORMALMAP) {
  43963. world.toNormalMatrix(this._normalMatrix);
  43964. this.bindOnlyNormalMatrix(this._normalMatrix);
  43965. }
  43966. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43967. // Bones
  43968. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43969. if (mustRebind) {
  43970. this._uniformBuffer.bindToEffect(effect, "Material");
  43971. this.bindViewProjection(effect);
  43972. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43973. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43974. // Fresnel
  43975. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43976. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43977. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43978. }
  43979. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43980. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43981. }
  43982. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43983. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43984. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43985. }
  43986. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43987. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43988. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43989. }
  43990. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43991. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43992. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43993. }
  43994. }
  43995. // Textures
  43996. if (scene.texturesEnabled) {
  43997. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43998. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43999. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44000. if (this._diffuseTexture.hasAlpha) {
  44001. effect.setFloat("alphaCutOff", this.alphaCutOff);
  44002. }
  44003. }
  44004. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44005. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44006. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44007. }
  44008. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44009. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44010. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44011. }
  44012. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44013. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44014. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44015. if (this._reflectionTexture.boundingBoxSize) {
  44016. var cubeTexture = this._reflectionTexture;
  44017. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44018. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44019. }
  44020. }
  44021. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44022. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44023. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44024. }
  44025. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44026. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44027. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44028. }
  44029. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44030. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44031. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44032. }
  44033. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44034. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44035. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44036. if (scene._mirroredCameraPosition) {
  44037. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44038. }
  44039. else {
  44040. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44041. }
  44042. }
  44043. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44044. var depth = 1.0;
  44045. if (!this._refractionTexture.isCube) {
  44046. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44047. if (this._refractionTexture.depth) {
  44048. depth = this._refractionTexture.depth;
  44049. }
  44050. }
  44051. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44052. }
  44053. }
  44054. // Point size
  44055. if (this.pointsCloud) {
  44056. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44057. }
  44058. if (defines.SPECULARTERM) {
  44059. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44060. }
  44061. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44062. // Diffuse
  44063. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44064. }
  44065. // Textures
  44066. if (scene.texturesEnabled) {
  44067. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44068. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44069. }
  44070. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44071. effect.setTexture("ambientSampler", this._ambientTexture);
  44072. }
  44073. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44074. effect.setTexture("opacitySampler", this._opacityTexture);
  44075. }
  44076. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44077. if (this._reflectionTexture.isCube) {
  44078. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44079. }
  44080. else {
  44081. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44082. }
  44083. }
  44084. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44085. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44086. }
  44087. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44088. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44089. }
  44090. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44091. effect.setTexture("specularSampler", this._specularTexture);
  44092. }
  44093. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44094. effect.setTexture("bumpSampler", this._bumpTexture);
  44095. }
  44096. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44097. var depth = 1.0;
  44098. if (this._refractionTexture.isCube) {
  44099. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44100. }
  44101. else {
  44102. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44103. }
  44104. }
  44105. }
  44106. // Clip plane
  44107. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44108. // Colors
  44109. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44110. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44111. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44112. }
  44113. if (mustRebind || !this.isFrozen) {
  44114. // Lights
  44115. if (scene.lightsEnabled && !this._disableLighting) {
  44116. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44117. }
  44118. // View
  44119. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44120. this.bindView(effect);
  44121. }
  44122. // Fog
  44123. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44124. // Morph targets
  44125. if (defines.NUM_MORPH_INFLUENCERS) {
  44126. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44127. }
  44128. // Log. depth
  44129. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44130. // image processing
  44131. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  44132. this._imageProcessingConfiguration.bind(this._activeEffect);
  44133. }
  44134. }
  44135. this._uniformBuffer.update();
  44136. this._afterBind(mesh, this._activeEffect);
  44137. };
  44138. StandardMaterial.prototype.getAnimatables = function () {
  44139. var results = [];
  44140. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44141. results.push(this._diffuseTexture);
  44142. }
  44143. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44144. results.push(this._ambientTexture);
  44145. }
  44146. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44147. results.push(this._opacityTexture);
  44148. }
  44149. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44150. results.push(this._reflectionTexture);
  44151. }
  44152. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44153. results.push(this._emissiveTexture);
  44154. }
  44155. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44156. results.push(this._specularTexture);
  44157. }
  44158. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44159. results.push(this._bumpTexture);
  44160. }
  44161. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44162. results.push(this._lightmapTexture);
  44163. }
  44164. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44165. results.push(this._refractionTexture);
  44166. }
  44167. return results;
  44168. };
  44169. StandardMaterial.prototype.getActiveTextures = function () {
  44170. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44171. if (this._diffuseTexture) {
  44172. activeTextures.push(this._diffuseTexture);
  44173. }
  44174. if (this._ambientTexture) {
  44175. activeTextures.push(this._ambientTexture);
  44176. }
  44177. if (this._opacityTexture) {
  44178. activeTextures.push(this._opacityTexture);
  44179. }
  44180. if (this._reflectionTexture) {
  44181. activeTextures.push(this._reflectionTexture);
  44182. }
  44183. if (this._emissiveTexture) {
  44184. activeTextures.push(this._emissiveTexture);
  44185. }
  44186. if (this._specularTexture) {
  44187. activeTextures.push(this._specularTexture);
  44188. }
  44189. if (this._bumpTexture) {
  44190. activeTextures.push(this._bumpTexture);
  44191. }
  44192. if (this._lightmapTexture) {
  44193. activeTextures.push(this._lightmapTexture);
  44194. }
  44195. if (this._refractionTexture) {
  44196. activeTextures.push(this._refractionTexture);
  44197. }
  44198. return activeTextures;
  44199. };
  44200. StandardMaterial.prototype.hasTexture = function (texture) {
  44201. if (_super.prototype.hasTexture.call(this, texture)) {
  44202. return true;
  44203. }
  44204. if (this._diffuseTexture === texture) {
  44205. return true;
  44206. }
  44207. if (this._ambientTexture === texture) {
  44208. return true;
  44209. }
  44210. if (this._opacityTexture === texture) {
  44211. return true;
  44212. }
  44213. if (this._reflectionTexture === texture) {
  44214. return true;
  44215. }
  44216. if (this._emissiveTexture === texture) {
  44217. return true;
  44218. }
  44219. if (this._specularTexture === texture) {
  44220. return true;
  44221. }
  44222. if (this._bumpTexture === texture) {
  44223. return true;
  44224. }
  44225. if (this._lightmapTexture === texture) {
  44226. return true;
  44227. }
  44228. if (this._refractionTexture === texture) {
  44229. return true;
  44230. }
  44231. return false;
  44232. };
  44233. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44234. if (forceDisposeTextures) {
  44235. if (this._diffuseTexture) {
  44236. this._diffuseTexture.dispose();
  44237. }
  44238. if (this._ambientTexture) {
  44239. this._ambientTexture.dispose();
  44240. }
  44241. if (this._opacityTexture) {
  44242. this._opacityTexture.dispose();
  44243. }
  44244. if (this._reflectionTexture) {
  44245. this._reflectionTexture.dispose();
  44246. }
  44247. if (this._emissiveTexture) {
  44248. this._emissiveTexture.dispose();
  44249. }
  44250. if (this._specularTexture) {
  44251. this._specularTexture.dispose();
  44252. }
  44253. if (this._bumpTexture) {
  44254. this._bumpTexture.dispose();
  44255. }
  44256. if (this._lightmapTexture) {
  44257. this._lightmapTexture.dispose();
  44258. }
  44259. if (this._refractionTexture) {
  44260. this._refractionTexture.dispose();
  44261. }
  44262. }
  44263. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44264. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44265. }
  44266. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44267. };
  44268. StandardMaterial.prototype.clone = function (name) {
  44269. var _this = this;
  44270. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44271. result.name = name;
  44272. result.id = name;
  44273. return result;
  44274. };
  44275. StandardMaterial.prototype.serialize = function () {
  44276. return BABYLON.SerializationHelper.Serialize(this);
  44277. };
  44278. // Statics
  44279. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44280. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44281. };
  44282. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44283. get: function () {
  44284. return StandardMaterial._DiffuseTextureEnabled;
  44285. },
  44286. set: function (value) {
  44287. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44288. return;
  44289. }
  44290. StandardMaterial._DiffuseTextureEnabled = value;
  44291. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44292. },
  44293. enumerable: true,
  44294. configurable: true
  44295. });
  44296. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44297. get: function () {
  44298. return StandardMaterial._AmbientTextureEnabled;
  44299. },
  44300. set: function (value) {
  44301. if (StandardMaterial._AmbientTextureEnabled === value) {
  44302. return;
  44303. }
  44304. StandardMaterial._AmbientTextureEnabled = value;
  44305. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44306. },
  44307. enumerable: true,
  44308. configurable: true
  44309. });
  44310. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44311. get: function () {
  44312. return StandardMaterial._OpacityTextureEnabled;
  44313. },
  44314. set: function (value) {
  44315. if (StandardMaterial._OpacityTextureEnabled === value) {
  44316. return;
  44317. }
  44318. StandardMaterial._OpacityTextureEnabled = value;
  44319. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44320. },
  44321. enumerable: true,
  44322. configurable: true
  44323. });
  44324. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44325. get: function () {
  44326. return StandardMaterial._ReflectionTextureEnabled;
  44327. },
  44328. set: function (value) {
  44329. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44330. return;
  44331. }
  44332. StandardMaterial._ReflectionTextureEnabled = value;
  44333. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44334. },
  44335. enumerable: true,
  44336. configurable: true
  44337. });
  44338. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44339. get: function () {
  44340. return StandardMaterial._EmissiveTextureEnabled;
  44341. },
  44342. set: function (value) {
  44343. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44344. return;
  44345. }
  44346. StandardMaterial._EmissiveTextureEnabled = value;
  44347. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44348. },
  44349. enumerable: true,
  44350. configurable: true
  44351. });
  44352. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44353. get: function () {
  44354. return StandardMaterial._SpecularTextureEnabled;
  44355. },
  44356. set: function (value) {
  44357. if (StandardMaterial._SpecularTextureEnabled === value) {
  44358. return;
  44359. }
  44360. StandardMaterial._SpecularTextureEnabled = value;
  44361. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44362. },
  44363. enumerable: true,
  44364. configurable: true
  44365. });
  44366. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44367. get: function () {
  44368. return StandardMaterial._BumpTextureEnabled;
  44369. },
  44370. set: function (value) {
  44371. if (StandardMaterial._BumpTextureEnabled === value) {
  44372. return;
  44373. }
  44374. StandardMaterial._BumpTextureEnabled = value;
  44375. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44376. },
  44377. enumerable: true,
  44378. configurable: true
  44379. });
  44380. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44381. get: function () {
  44382. return StandardMaterial._LightmapTextureEnabled;
  44383. },
  44384. set: function (value) {
  44385. if (StandardMaterial._LightmapTextureEnabled === value) {
  44386. return;
  44387. }
  44388. StandardMaterial._LightmapTextureEnabled = value;
  44389. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44390. },
  44391. enumerable: true,
  44392. configurable: true
  44393. });
  44394. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44395. get: function () {
  44396. return StandardMaterial._RefractionTextureEnabled;
  44397. },
  44398. set: function (value) {
  44399. if (StandardMaterial._RefractionTextureEnabled === value) {
  44400. return;
  44401. }
  44402. StandardMaterial._RefractionTextureEnabled = value;
  44403. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44404. },
  44405. enumerable: true,
  44406. configurable: true
  44407. });
  44408. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44409. get: function () {
  44410. return StandardMaterial._ColorGradingTextureEnabled;
  44411. },
  44412. set: function (value) {
  44413. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44414. return;
  44415. }
  44416. StandardMaterial._ColorGradingTextureEnabled = value;
  44417. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44418. },
  44419. enumerable: true,
  44420. configurable: true
  44421. });
  44422. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44423. get: function () {
  44424. return StandardMaterial._FresnelEnabled;
  44425. },
  44426. set: function (value) {
  44427. if (StandardMaterial._FresnelEnabled === value) {
  44428. return;
  44429. }
  44430. StandardMaterial._FresnelEnabled = value;
  44431. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44432. },
  44433. enumerable: true,
  44434. configurable: true
  44435. });
  44436. // Flags used to enable or disable a type of texture for all Standard Materials
  44437. StandardMaterial._DiffuseTextureEnabled = true;
  44438. StandardMaterial._AmbientTextureEnabled = true;
  44439. StandardMaterial._OpacityTextureEnabled = true;
  44440. StandardMaterial._ReflectionTextureEnabled = true;
  44441. StandardMaterial._EmissiveTextureEnabled = true;
  44442. StandardMaterial._SpecularTextureEnabled = true;
  44443. StandardMaterial._BumpTextureEnabled = true;
  44444. StandardMaterial._LightmapTextureEnabled = true;
  44445. StandardMaterial._RefractionTextureEnabled = true;
  44446. StandardMaterial._ColorGradingTextureEnabled = true;
  44447. StandardMaterial._FresnelEnabled = true;
  44448. __decorate([
  44449. BABYLON.serializeAsTexture("diffuseTexture")
  44450. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44451. __decorate([
  44452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44453. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44454. __decorate([
  44455. BABYLON.serializeAsTexture("ambientTexture")
  44456. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44457. __decorate([
  44458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44459. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44460. __decorate([
  44461. BABYLON.serializeAsTexture("opacityTexture")
  44462. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44463. __decorate([
  44464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44465. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44466. __decorate([
  44467. BABYLON.serializeAsTexture("reflectionTexture")
  44468. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44469. __decorate([
  44470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44471. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44472. __decorate([
  44473. BABYLON.serializeAsTexture("emissiveTexture")
  44474. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44475. __decorate([
  44476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44477. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44478. __decorate([
  44479. BABYLON.serializeAsTexture("specularTexture")
  44480. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44481. __decorate([
  44482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44483. ], StandardMaterial.prototype, "specularTexture", void 0);
  44484. __decorate([
  44485. BABYLON.serializeAsTexture("bumpTexture")
  44486. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44487. __decorate([
  44488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44489. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44490. __decorate([
  44491. BABYLON.serializeAsTexture("lightmapTexture")
  44492. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44493. __decorate([
  44494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44495. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44496. __decorate([
  44497. BABYLON.serializeAsTexture("refractionTexture")
  44498. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44499. __decorate([
  44500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44501. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44502. __decorate([
  44503. BABYLON.serializeAsColor3("ambient")
  44504. ], StandardMaterial.prototype, "ambientColor", void 0);
  44505. __decorate([
  44506. BABYLON.serializeAsColor3("diffuse")
  44507. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44508. __decorate([
  44509. BABYLON.serializeAsColor3("specular")
  44510. ], StandardMaterial.prototype, "specularColor", void 0);
  44511. __decorate([
  44512. BABYLON.serializeAsColor3("emissive")
  44513. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44514. __decorate([
  44515. BABYLON.serialize()
  44516. ], StandardMaterial.prototype, "specularPower", void 0);
  44517. __decorate([
  44518. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44519. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44520. __decorate([
  44521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44522. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44523. __decorate([
  44524. BABYLON.serialize("useEmissiveAsIllumination")
  44525. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44526. __decorate([
  44527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44528. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44529. __decorate([
  44530. BABYLON.serialize("linkEmissiveWithDiffuse")
  44531. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44532. __decorate([
  44533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44534. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44535. __decorate([
  44536. BABYLON.serialize("useSpecularOverAlpha")
  44537. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44538. __decorate([
  44539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44540. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44541. __decorate([
  44542. BABYLON.serialize("useReflectionOverAlpha")
  44543. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44544. __decorate([
  44545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44546. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44547. __decorate([
  44548. BABYLON.serialize("disableLighting")
  44549. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44550. __decorate([
  44551. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44552. ], StandardMaterial.prototype, "disableLighting", void 0);
  44553. __decorate([
  44554. BABYLON.serialize("useObjectSpaceNormalMap")
  44555. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44556. __decorate([
  44557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44558. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44559. __decorate([
  44560. BABYLON.serialize("useParallax")
  44561. ], StandardMaterial.prototype, "_useParallax", void 0);
  44562. __decorate([
  44563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44564. ], StandardMaterial.prototype, "useParallax", void 0);
  44565. __decorate([
  44566. BABYLON.serialize("useParallaxOcclusion")
  44567. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44568. __decorate([
  44569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44570. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44571. __decorate([
  44572. BABYLON.serialize()
  44573. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44574. __decorate([
  44575. BABYLON.serialize("roughness")
  44576. ], StandardMaterial.prototype, "_roughness", void 0);
  44577. __decorate([
  44578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44579. ], StandardMaterial.prototype, "roughness", void 0);
  44580. __decorate([
  44581. BABYLON.serialize()
  44582. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44583. __decorate([
  44584. BABYLON.serialize()
  44585. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44586. __decorate([
  44587. BABYLON.serialize()
  44588. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44589. __decorate([
  44590. BABYLON.serialize("useLightmapAsShadowmap")
  44591. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44592. __decorate([
  44593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44594. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44595. __decorate([
  44596. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44597. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44598. __decorate([
  44599. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44600. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44601. __decorate([
  44602. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44603. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44604. __decorate([
  44605. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44606. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44607. __decorate([
  44608. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44609. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44610. __decorate([
  44611. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44612. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44613. __decorate([
  44614. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44615. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44616. __decorate([
  44617. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44618. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44619. __decorate([
  44620. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44621. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44622. __decorate([
  44623. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44624. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44625. __decorate([
  44626. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44627. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44628. __decorate([
  44629. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44630. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44631. __decorate([
  44632. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44633. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44634. __decorate([
  44635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44636. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44637. __decorate([
  44638. BABYLON.serialize("maxSimultaneousLights")
  44639. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44640. __decorate([
  44641. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44642. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44643. __decorate([
  44644. BABYLON.serialize("invertNormalMapX")
  44645. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44646. __decorate([
  44647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44648. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44649. __decorate([
  44650. BABYLON.serialize("invertNormalMapY")
  44651. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44652. __decorate([
  44653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44654. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44655. __decorate([
  44656. BABYLON.serialize("twoSidedLighting")
  44657. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44658. __decorate([
  44659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44660. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44661. __decorate([
  44662. BABYLON.serialize()
  44663. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44664. return StandardMaterial;
  44665. }(BABYLON.PushMaterial));
  44666. BABYLON.StandardMaterial = StandardMaterial;
  44667. })(BABYLON || (BABYLON = {}));
  44668. //# sourceMappingURL=babylon.standardMaterial.js.map
  44669. var BABYLON;
  44670. (function (BABYLON) {
  44671. /**
  44672. * Manages the defines for the PBR Material.
  44673. * @hiddenChildren
  44674. */
  44675. var PBRMaterialDefines = /** @class */ (function (_super) {
  44676. __extends(PBRMaterialDefines, _super);
  44677. /**
  44678. * Initializes the PBR Material defines.
  44679. */
  44680. function PBRMaterialDefines() {
  44681. var _this = _super.call(this) || this;
  44682. _this.PBR = true;
  44683. _this.MAINUV1 = false;
  44684. _this.MAINUV2 = false;
  44685. _this.UV1 = false;
  44686. _this.UV2 = false;
  44687. _this.ALBEDO = false;
  44688. _this.ALBEDODIRECTUV = 0;
  44689. _this.VERTEXCOLOR = false;
  44690. _this.AMBIENT = false;
  44691. _this.AMBIENTDIRECTUV = 0;
  44692. _this.AMBIENTINGRAYSCALE = false;
  44693. _this.OPACITY = false;
  44694. _this.VERTEXALPHA = false;
  44695. _this.OPACITYDIRECTUV = 0;
  44696. _this.OPACITYRGB = false;
  44697. _this.ALPHATEST = false;
  44698. _this.DEPTHPREPASS = false;
  44699. _this.ALPHABLEND = false;
  44700. _this.ALPHAFROMALBEDO = false;
  44701. _this.ALPHATESTVALUE = "0.5";
  44702. _this.SPECULAROVERALPHA = false;
  44703. _this.RADIANCEOVERALPHA = false;
  44704. _this.ALPHAFRESNEL = false;
  44705. _this.LINEARALPHAFRESNEL = false;
  44706. _this.PREMULTIPLYALPHA = false;
  44707. _this.EMISSIVE = false;
  44708. _this.EMISSIVEDIRECTUV = 0;
  44709. _this.REFLECTIVITY = false;
  44710. _this.REFLECTIVITYDIRECTUV = 0;
  44711. _this.SPECULARTERM = false;
  44712. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44713. _this.MICROSURFACEAUTOMATIC = false;
  44714. _this.LODBASEDMICROSFURACE = false;
  44715. _this.MICROSURFACEMAP = false;
  44716. _this.MICROSURFACEMAPDIRECTUV = 0;
  44717. _this.METALLICWORKFLOW = false;
  44718. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44719. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44720. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44721. _this.AOSTOREINMETALMAPRED = false;
  44722. _this.ENVIRONMENTBRDF = false;
  44723. _this.NORMAL = false;
  44724. _this.TANGENT = false;
  44725. _this.BUMP = false;
  44726. _this.BUMPDIRECTUV = 0;
  44727. _this.OBJECTSPACE_NORMALMAP = false;
  44728. _this.PARALLAX = false;
  44729. _this.PARALLAXOCCLUSION = false;
  44730. _this.NORMALXYSCALE = true;
  44731. _this.LIGHTMAP = false;
  44732. _this.LIGHTMAPDIRECTUV = 0;
  44733. _this.USELIGHTMAPASSHADOWMAP = false;
  44734. _this.GAMMALIGHTMAP = false;
  44735. _this.REFLECTION = false;
  44736. _this.REFLECTIONMAP_3D = false;
  44737. _this.REFLECTIONMAP_SPHERICAL = false;
  44738. _this.REFLECTIONMAP_PLANAR = false;
  44739. _this.REFLECTIONMAP_CUBIC = false;
  44740. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44741. _this.REFLECTIONMAP_PROJECTION = false;
  44742. _this.REFLECTIONMAP_SKYBOX = false;
  44743. _this.REFLECTIONMAP_EXPLICIT = false;
  44744. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44745. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44746. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44747. _this.INVERTCUBICMAP = false;
  44748. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44749. _this.USESPHERICALINVERTEX = false;
  44750. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44751. _this.LODINREFLECTIONALPHA = false;
  44752. _this.GAMMAREFLECTION = false;
  44753. _this.RGBDREFLECTION = false;
  44754. _this.RADIANCEOCCLUSION = false;
  44755. _this.HORIZONOCCLUSION = false;
  44756. _this.REFRACTION = false;
  44757. _this.REFRACTIONMAP_3D = false;
  44758. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44759. _this.LODINREFRACTIONALPHA = false;
  44760. _this.GAMMAREFRACTION = false;
  44761. _this.RGBDREFRACTION = false;
  44762. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44763. _this.INSTANCES = false;
  44764. _this.NUM_BONE_INFLUENCERS = 0;
  44765. _this.BonesPerMesh = 0;
  44766. _this.NONUNIFORMSCALING = false;
  44767. _this.MORPHTARGETS = false;
  44768. _this.MORPHTARGETS_NORMAL = false;
  44769. _this.MORPHTARGETS_TANGENT = false;
  44770. _this.NUM_MORPH_INFLUENCERS = 0;
  44771. _this.IMAGEPROCESSING = false;
  44772. _this.VIGNETTE = false;
  44773. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44774. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44775. _this.TONEMAPPING = false;
  44776. _this.CONTRAST = false;
  44777. _this.COLORCURVES = false;
  44778. _this.COLORGRADING = false;
  44779. _this.COLORGRADING3D = false;
  44780. _this.SAMPLER3DGREENDEPTH = false;
  44781. _this.SAMPLER3DBGRMAP = false;
  44782. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44783. _this.EXPOSURE = false;
  44784. _this.USEPHYSICALLIGHTFALLOFF = false;
  44785. _this.TWOSIDEDLIGHTING = false;
  44786. _this.SHADOWFLOAT = false;
  44787. _this.CLIPPLANE = false;
  44788. _this.POINTSIZE = false;
  44789. _this.FOG = false;
  44790. _this.LOGARITHMICDEPTH = false;
  44791. _this.FORCENORMALFORWARD = false;
  44792. _this.SPECULARAA = false;
  44793. _this.UNLIT = false;
  44794. _this.rebuild();
  44795. return _this;
  44796. }
  44797. /**
  44798. * Resets the PBR Material defines.
  44799. */
  44800. PBRMaterialDefines.prototype.reset = function () {
  44801. _super.prototype.reset.call(this);
  44802. this.ALPHATESTVALUE = "0.5";
  44803. this.PBR = true;
  44804. };
  44805. return PBRMaterialDefines;
  44806. }(BABYLON.MaterialDefines));
  44807. /**
  44808. * The Physically based material base class of BJS.
  44809. *
  44810. * This offers the main features of a standard PBR material.
  44811. * For more information, please refer to the documentation :
  44812. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44813. */
  44814. var PBRBaseMaterial = /** @class */ (function (_super) {
  44815. __extends(PBRBaseMaterial, _super);
  44816. /**
  44817. * Instantiates a new PBRMaterial instance.
  44818. *
  44819. * @param name The material name
  44820. * @param scene The scene the material will be use in.
  44821. */
  44822. function PBRBaseMaterial(name, scene) {
  44823. var _this = _super.call(this, name, scene) || this;
  44824. /**
  44825. * Intensity of the direct lights e.g. the four lights available in your scene.
  44826. * This impacts both the direct diffuse and specular highlights.
  44827. */
  44828. _this._directIntensity = 1.0;
  44829. /**
  44830. * Intensity of the emissive part of the material.
  44831. * This helps controlling the emissive effect without modifying the emissive color.
  44832. */
  44833. _this._emissiveIntensity = 1.0;
  44834. /**
  44835. * Intensity of the environment e.g. how much the environment will light the object
  44836. * either through harmonics for rough material or through the refelction for shiny ones.
  44837. */
  44838. _this._environmentIntensity = 1.0;
  44839. /**
  44840. * This is a special control allowing the reduction of the specular highlights coming from the
  44841. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44842. */
  44843. _this._specularIntensity = 1.0;
  44844. /**
  44845. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44846. */
  44847. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44848. /**
  44849. * Debug Control allowing disabling the bump map on this material.
  44850. */
  44851. _this._disableBumpMap = false;
  44852. /**
  44853. * AKA Occlusion Texture Intensity in other nomenclature.
  44854. */
  44855. _this._ambientTextureStrength = 1.0;
  44856. /**
  44857. * The color of a material in ambient lighting.
  44858. */
  44859. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44860. /**
  44861. * AKA Diffuse Color in other nomenclature.
  44862. */
  44863. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44864. /**
  44865. * AKA Specular Color in other nomenclature.
  44866. */
  44867. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44868. /**
  44869. * The color applied when light is reflected from a material.
  44870. */
  44871. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44872. /**
  44873. * The color applied when light is emitted from a material.
  44874. */
  44875. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44876. /**
  44877. * AKA Glossiness in other nomenclature.
  44878. */
  44879. _this._microSurface = 0.9;
  44880. /**
  44881. * source material index of refraction (IOR)' / 'destination material IOR.
  44882. */
  44883. _this._indexOfRefraction = 0.66;
  44884. /**
  44885. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44886. */
  44887. _this._invertRefractionY = false;
  44888. /**
  44889. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44890. * Materials half opaque for instance using refraction could benefit from this control.
  44891. */
  44892. _this._linkRefractionWithTransparency = false;
  44893. /**
  44894. * Specifies that the material will use the light map as a show map.
  44895. */
  44896. _this._useLightmapAsShadowmap = false;
  44897. /**
  44898. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44899. * makes the reflect vector face the model (under horizon).
  44900. */
  44901. _this._useHorizonOcclusion = true;
  44902. /**
  44903. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44904. * too much the area relying on ambient texture to define their ambient occlusion.
  44905. */
  44906. _this._useRadianceOcclusion = true;
  44907. /**
  44908. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44909. */
  44910. _this._useAlphaFromAlbedoTexture = false;
  44911. /**
  44912. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44913. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44914. */
  44915. _this._useSpecularOverAlpha = true;
  44916. /**
  44917. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44918. */
  44919. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44920. /**
  44921. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44922. */
  44923. _this._useRoughnessFromMetallicTextureAlpha = true;
  44924. /**
  44925. * Specifies if the metallic texture contains the roughness information in its green channel.
  44926. */
  44927. _this._useRoughnessFromMetallicTextureGreen = false;
  44928. /**
  44929. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44930. */
  44931. _this._useMetallnessFromMetallicTextureBlue = false;
  44932. /**
  44933. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44934. */
  44935. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44936. /**
  44937. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44938. */
  44939. _this._useAmbientInGrayScale = false;
  44940. /**
  44941. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44942. * The material will try to infer what glossiness each pixel should be.
  44943. */
  44944. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44945. /**
  44946. * BJS is using an harcoded light falloff based on a manually sets up range.
  44947. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44948. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44949. */
  44950. _this._usePhysicalLightFalloff = true;
  44951. /**
  44952. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44953. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44954. */
  44955. _this._useRadianceOverAlpha = true;
  44956. /**
  44957. * Allows using an object space normal map (instead of tangent space).
  44958. */
  44959. _this._useObjectSpaceNormalMap = false;
  44960. /**
  44961. * Allows using the bump map in parallax mode.
  44962. */
  44963. _this._useParallax = false;
  44964. /**
  44965. * Allows using the bump map in parallax occlusion mode.
  44966. */
  44967. _this._useParallaxOcclusion = false;
  44968. /**
  44969. * Controls the scale bias of the parallax mode.
  44970. */
  44971. _this._parallaxScaleBias = 0.05;
  44972. /**
  44973. * If sets to true, disables all the lights affecting the material.
  44974. */
  44975. _this._disableLighting = false;
  44976. /**
  44977. * Number of Simultaneous lights allowed on the material.
  44978. */
  44979. _this._maxSimultaneousLights = 4;
  44980. /**
  44981. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44982. */
  44983. _this._invertNormalMapX = false;
  44984. /**
  44985. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44986. */
  44987. _this._invertNormalMapY = false;
  44988. /**
  44989. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44990. */
  44991. _this._twoSidedLighting = false;
  44992. /**
  44993. * Defines the alpha limits in alpha test mode.
  44994. */
  44995. _this._alphaCutOff = 0.4;
  44996. /**
  44997. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44998. */
  44999. _this._forceAlphaTest = false;
  45000. /**
  45001. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45002. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45003. */
  45004. _this._useAlphaFresnel = false;
  45005. /**
  45006. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45007. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45008. */
  45009. _this._useLinearAlphaFresnel = false;
  45010. /**
  45011. * The transparency mode of the material.
  45012. */
  45013. _this._transparencyMode = null;
  45014. /**
  45015. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45016. * from cos thetav and roughness:
  45017. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45018. */
  45019. _this._environmentBRDFTexture = null;
  45020. /**
  45021. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45022. */
  45023. _this._forceIrradianceInFragment = false;
  45024. /**
  45025. * Force normal to face away from face.
  45026. */
  45027. _this._forceNormalForward = false;
  45028. /**
  45029. * Enables specular anti aliasing in the PBR shader.
  45030. * It will both interacts on the Geometry for analytical and IBL lighting.
  45031. * It also prefilter the roughness map based on the bump values.
  45032. */
  45033. _this._enableSpecularAntiAliasing = false;
  45034. /**
  45035. * Stores the available render targets.
  45036. */
  45037. _this._renderTargets = new BABYLON.SmartArray(16);
  45038. /**
  45039. * Sets the global ambient color for the material used in lighting calculations.
  45040. */
  45041. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45042. /**
  45043. * If set to true, no lighting calculations will be applied.
  45044. */
  45045. _this._unlit = false;
  45046. // Setup the default processing configuration to the scene.
  45047. _this._attachImageProcessingConfiguration(null);
  45048. _this.getRenderTargetTextures = function () {
  45049. _this._renderTargets.reset();
  45050. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45051. _this._renderTargets.push(_this._reflectionTexture);
  45052. }
  45053. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45054. _this._renderTargets.push(_this._refractionTexture);
  45055. }
  45056. return _this._renderTargets;
  45057. };
  45058. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45059. return _this;
  45060. }
  45061. /**
  45062. * Attaches a new image processing configuration to the PBR Material.
  45063. * @param configuration
  45064. */
  45065. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45066. var _this = this;
  45067. if (configuration === this._imageProcessingConfiguration) {
  45068. return;
  45069. }
  45070. // Detaches observer.
  45071. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45072. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45073. }
  45074. // Pick the scene configuration if needed.
  45075. if (!configuration) {
  45076. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45077. }
  45078. else {
  45079. this._imageProcessingConfiguration = configuration;
  45080. }
  45081. // Attaches observer.
  45082. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45083. _this._markAllSubMeshesAsImageProcessingDirty();
  45084. });
  45085. };
  45086. /**
  45087. * Gets the name of the material class.
  45088. */
  45089. PBRBaseMaterial.prototype.getClassName = function () {
  45090. return "PBRBaseMaterial";
  45091. };
  45092. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45093. /**
  45094. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45095. */
  45096. get: function () {
  45097. return this._useLogarithmicDepth;
  45098. },
  45099. /**
  45100. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45101. */
  45102. set: function (value) {
  45103. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45104. },
  45105. enumerable: true,
  45106. configurable: true
  45107. });
  45108. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45109. /**
  45110. * Gets the current transparency mode.
  45111. */
  45112. get: function () {
  45113. return this._transparencyMode;
  45114. },
  45115. /**
  45116. * Sets the transparency mode of the material.
  45117. *
  45118. * | Value | Type | Description |
  45119. * | ----- | ----------------------------------- | ----------- |
  45120. * | 0 | OPAQUE | |
  45121. * | 1 | ALPHATEST | |
  45122. * | 2 | ALPHABLEND | |
  45123. * | 3 | ALPHATESTANDBLEND | |
  45124. *
  45125. */
  45126. set: function (value) {
  45127. if (this._transparencyMode === value) {
  45128. return;
  45129. }
  45130. this._transparencyMode = value;
  45131. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45132. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45133. },
  45134. enumerable: true,
  45135. configurable: true
  45136. });
  45137. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45138. /**
  45139. * Returns true if alpha blending should be disabled.
  45140. */
  45141. get: function () {
  45142. return (this._linkRefractionWithTransparency ||
  45143. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45144. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45145. },
  45146. enumerable: true,
  45147. configurable: true
  45148. });
  45149. /**
  45150. * Specifies whether or not this material should be rendered in alpha blend mode.
  45151. */
  45152. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45153. if (this._disableAlphaBlending) {
  45154. return false;
  45155. }
  45156. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45157. };
  45158. /**
  45159. * Specifies if the mesh will require alpha blending.
  45160. * @param mesh - BJS mesh.
  45161. */
  45162. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45163. if (this._disableAlphaBlending) {
  45164. return false;
  45165. }
  45166. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45167. };
  45168. /**
  45169. * Specifies whether or not this material should be rendered in alpha test mode.
  45170. */
  45171. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45172. if (this._forceAlphaTest) {
  45173. return true;
  45174. }
  45175. if (this._linkRefractionWithTransparency) {
  45176. return false;
  45177. }
  45178. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45179. };
  45180. /**
  45181. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45182. */
  45183. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45184. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45185. };
  45186. /**
  45187. * Gets the texture used for the alpha test.
  45188. */
  45189. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45190. return this._albedoTexture;
  45191. };
  45192. /**
  45193. * Specifies that the submesh is ready to be used.
  45194. * @param mesh - BJS mesh.
  45195. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45196. * @param useInstances - Specifies that instances should be used.
  45197. * @returns - boolean indicating that the submesh is ready or not.
  45198. */
  45199. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45200. if (subMesh.effect && this.isFrozen) {
  45201. if (this._wasPreviouslyReady) {
  45202. return true;
  45203. }
  45204. }
  45205. if (!subMesh._materialDefines) {
  45206. subMesh._materialDefines = new PBRMaterialDefines();
  45207. }
  45208. var defines = subMesh._materialDefines;
  45209. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45210. if (defines._renderId === this.getScene().getRenderId()) {
  45211. return true;
  45212. }
  45213. }
  45214. var scene = this.getScene();
  45215. var engine = scene.getEngine();
  45216. if (defines._areTexturesDirty) {
  45217. if (scene.texturesEnabled) {
  45218. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45219. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45220. return false;
  45221. }
  45222. }
  45223. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45224. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45225. return false;
  45226. }
  45227. }
  45228. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45229. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45230. return false;
  45231. }
  45232. }
  45233. var reflectionTexture = this._getReflectionTexture();
  45234. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45235. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45236. return false;
  45237. }
  45238. }
  45239. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45240. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45241. return false;
  45242. }
  45243. }
  45244. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45245. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45246. return false;
  45247. }
  45248. }
  45249. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45250. if (this._metallicTexture) {
  45251. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45252. return false;
  45253. }
  45254. }
  45255. else if (this._reflectivityTexture) {
  45256. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45257. return false;
  45258. }
  45259. }
  45260. if (this._microSurfaceTexture) {
  45261. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45262. return false;
  45263. }
  45264. }
  45265. }
  45266. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45267. // Bump texture cannot be not blocking.
  45268. if (!this._bumpTexture.isReady()) {
  45269. return false;
  45270. }
  45271. }
  45272. var refractionTexture = this._getRefractionTexture();
  45273. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45274. if (!refractionTexture.isReadyOrNotBlocking()) {
  45275. return false;
  45276. }
  45277. }
  45278. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45279. // This is blocking.
  45280. if (!this._environmentBRDFTexture.isReady()) {
  45281. return false;
  45282. }
  45283. }
  45284. }
  45285. }
  45286. if (defines._areImageProcessingDirty) {
  45287. if (!this._imageProcessingConfiguration.isReady()) {
  45288. return false;
  45289. }
  45290. }
  45291. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45292. mesh.createNormals(true);
  45293. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45294. }
  45295. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45296. if (effect) {
  45297. scene.resetCachedMaterial();
  45298. subMesh.setEffect(effect, defines);
  45299. this.buildUniformLayout();
  45300. }
  45301. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45302. return false;
  45303. }
  45304. defines._renderId = scene.getRenderId();
  45305. this._wasPreviouslyReady = true;
  45306. return true;
  45307. };
  45308. /**
  45309. * Specifies if the material uses metallic roughness workflow.
  45310. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45311. */
  45312. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45313. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45314. return true;
  45315. }
  45316. return false;
  45317. };
  45318. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45319. if (onCompiled === void 0) { onCompiled = null; }
  45320. if (onError === void 0) { onError = null; }
  45321. if (useInstances === void 0) { useInstances = null; }
  45322. if (useClipPlane === void 0) { useClipPlane = null; }
  45323. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45324. if (!defines.isDirty) {
  45325. return null;
  45326. }
  45327. defines.markAsProcessed();
  45328. var scene = this.getScene();
  45329. var engine = scene.getEngine();
  45330. // Fallbacks
  45331. var fallbacks = new BABYLON.EffectFallbacks();
  45332. var fallbackRank = 0;
  45333. if (defines.USESPHERICALINVERTEX) {
  45334. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45335. }
  45336. if (defines.FOG) {
  45337. fallbacks.addFallback(fallbackRank, "FOG");
  45338. }
  45339. if (defines.SPECULARAA) {
  45340. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45341. }
  45342. if (defines.POINTSIZE) {
  45343. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45344. }
  45345. if (defines.LOGARITHMICDEPTH) {
  45346. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45347. }
  45348. if (defines.PARALLAX) {
  45349. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45350. }
  45351. if (defines.PARALLAXOCCLUSION) {
  45352. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45353. }
  45354. if (defines.ENVIRONMENTBRDF) {
  45355. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45356. }
  45357. if (defines.TANGENT) {
  45358. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45359. }
  45360. if (defines.BUMP) {
  45361. fallbacks.addFallback(fallbackRank++, "BUMP");
  45362. }
  45363. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45364. if (defines.SPECULARTERM) {
  45365. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45366. }
  45367. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45368. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45369. }
  45370. if (defines.LIGHTMAP) {
  45371. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45372. }
  45373. if (defines.NORMAL) {
  45374. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45375. }
  45376. if (defines.AMBIENT) {
  45377. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45378. }
  45379. if (defines.EMISSIVE) {
  45380. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45381. }
  45382. if (defines.VERTEXCOLOR) {
  45383. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45384. }
  45385. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45386. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45387. }
  45388. if (defines.MORPHTARGETS) {
  45389. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45390. }
  45391. //Attributes
  45392. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45393. if (defines.NORMAL) {
  45394. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45395. }
  45396. if (defines.TANGENT) {
  45397. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45398. }
  45399. if (defines.UV1) {
  45400. attribs.push(BABYLON.VertexBuffer.UVKind);
  45401. }
  45402. if (defines.UV2) {
  45403. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45404. }
  45405. if (defines.VERTEXCOLOR) {
  45406. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45407. }
  45408. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45409. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45410. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45411. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45412. "vFogInfos", "vFogColor", "pointSize",
  45413. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45414. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45415. "mBones",
  45416. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45417. "vLightingIntensity",
  45418. "logarithmicDepthConstant",
  45419. "vSphericalX", "vSphericalY", "vSphericalZ",
  45420. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45421. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45422. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45423. "vTangentSpaceParams"
  45424. ];
  45425. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45426. "bumpSampler", "lightmapSampler", "opacitySampler",
  45427. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45428. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45429. "microSurfaceSampler", "environmentBrdfSampler"];
  45430. var uniformBuffers = ["Material", "Scene"];
  45431. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45432. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45433. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45434. uniformsNames: uniforms,
  45435. uniformBuffersNames: uniformBuffers,
  45436. samplers: samplers,
  45437. defines: defines,
  45438. maxSimultaneousLights: this._maxSimultaneousLights
  45439. });
  45440. var join = defines.toString();
  45441. return engine.createEffect("pbr", {
  45442. attributes: attribs,
  45443. uniformsNames: uniforms,
  45444. uniformBuffersNames: uniformBuffers,
  45445. samplers: samplers,
  45446. defines: join,
  45447. fallbacks: fallbacks,
  45448. onCompiled: onCompiled,
  45449. onError: onError,
  45450. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45451. }, engine);
  45452. };
  45453. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45454. if (useInstances === void 0) { useInstances = null; }
  45455. if (useClipPlane === void 0) { useClipPlane = null; }
  45456. var scene = this.getScene();
  45457. var engine = scene.getEngine();
  45458. // Lights
  45459. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45460. defines._needNormals = true;
  45461. // Textures
  45462. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45463. if (defines._areTexturesDirty) {
  45464. defines._needUVs = false;
  45465. if (scene.texturesEnabled) {
  45466. if (scene.getEngine().getCaps().textureLOD) {
  45467. defines.LODBASEDMICROSFURACE = true;
  45468. }
  45469. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45470. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45471. }
  45472. else {
  45473. defines.ALBEDO = false;
  45474. }
  45475. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45476. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45477. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45478. }
  45479. else {
  45480. defines.AMBIENT = false;
  45481. }
  45482. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45483. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45484. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45485. }
  45486. else {
  45487. defines.OPACITY = false;
  45488. }
  45489. var reflectionTexture = this._getReflectionTexture();
  45490. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45491. defines.REFLECTION = true;
  45492. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45493. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45494. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45495. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45496. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45497. defines.INVERTCUBICMAP = true;
  45498. }
  45499. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45500. switch (reflectionTexture.coordinatesMode) {
  45501. case BABYLON.Texture.EXPLICIT_MODE:
  45502. defines.REFLECTIONMAP_EXPLICIT = true;
  45503. break;
  45504. case BABYLON.Texture.PLANAR_MODE:
  45505. defines.REFLECTIONMAP_PLANAR = true;
  45506. break;
  45507. case BABYLON.Texture.PROJECTION_MODE:
  45508. defines.REFLECTIONMAP_PROJECTION = true;
  45509. break;
  45510. case BABYLON.Texture.SKYBOX_MODE:
  45511. defines.REFLECTIONMAP_SKYBOX = true;
  45512. break;
  45513. case BABYLON.Texture.SPHERICAL_MODE:
  45514. defines.REFLECTIONMAP_SPHERICAL = true;
  45515. break;
  45516. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45517. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45518. break;
  45519. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45520. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45521. break;
  45522. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45523. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45524. break;
  45525. case BABYLON.Texture.CUBIC_MODE:
  45526. case BABYLON.Texture.INVCUBIC_MODE:
  45527. default:
  45528. defines.REFLECTIONMAP_CUBIC = true;
  45529. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45530. break;
  45531. }
  45532. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45533. if (reflectionTexture.sphericalPolynomial) {
  45534. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45535. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45536. defines.USESPHERICALINVERTEX = false;
  45537. }
  45538. else {
  45539. defines.USESPHERICALINVERTEX = true;
  45540. }
  45541. }
  45542. }
  45543. }
  45544. else {
  45545. defines.REFLECTION = false;
  45546. defines.REFLECTIONMAP_3D = false;
  45547. defines.REFLECTIONMAP_SPHERICAL = false;
  45548. defines.REFLECTIONMAP_PLANAR = false;
  45549. defines.REFLECTIONMAP_CUBIC = false;
  45550. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45551. defines.REFLECTIONMAP_PROJECTION = false;
  45552. defines.REFLECTIONMAP_SKYBOX = false;
  45553. defines.REFLECTIONMAP_EXPLICIT = false;
  45554. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45555. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45556. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45557. defines.INVERTCUBICMAP = false;
  45558. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45559. defines.USESPHERICALINVERTEX = false;
  45560. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45561. defines.LODINREFLECTIONALPHA = false;
  45562. defines.GAMMAREFLECTION = false;
  45563. defines.RGBDREFLECTION = false;
  45564. }
  45565. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45566. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45567. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45568. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45569. }
  45570. else {
  45571. defines.LIGHTMAP = false;
  45572. }
  45573. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45574. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45575. }
  45576. else {
  45577. defines.EMISSIVE = false;
  45578. }
  45579. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45580. if (this._metallicTexture) {
  45581. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45582. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45583. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45584. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45585. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45586. }
  45587. else if (this._reflectivityTexture) {
  45588. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45589. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45590. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45591. }
  45592. else {
  45593. defines.REFLECTIVITY = false;
  45594. }
  45595. if (this._microSurfaceTexture) {
  45596. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45597. }
  45598. else {
  45599. defines.MICROSURFACEMAP = false;
  45600. }
  45601. }
  45602. else {
  45603. defines.REFLECTIVITY = false;
  45604. defines.MICROSURFACEMAP = false;
  45605. }
  45606. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45607. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45608. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45609. defines.PARALLAX = true;
  45610. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45611. }
  45612. else {
  45613. defines.PARALLAX = false;
  45614. }
  45615. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45616. }
  45617. else {
  45618. defines.BUMP = false;
  45619. }
  45620. var refractionTexture = this._getRefractionTexture();
  45621. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45622. defines.REFRACTION = true;
  45623. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45624. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45625. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45626. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45627. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45628. if (this._linkRefractionWithTransparency) {
  45629. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45630. }
  45631. }
  45632. else {
  45633. defines.REFRACTION = false;
  45634. }
  45635. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45636. defines.ENVIRONMENTBRDF = true;
  45637. }
  45638. else {
  45639. defines.ENVIRONMENTBRDF = false;
  45640. }
  45641. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45642. defines.ALPHAFROMALBEDO = true;
  45643. }
  45644. else {
  45645. defines.ALPHAFROMALBEDO = false;
  45646. }
  45647. }
  45648. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45649. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45650. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45651. if (!this.backFaceCulling && this._twoSidedLighting) {
  45652. defines.TWOSIDEDLIGHTING = true;
  45653. }
  45654. else {
  45655. defines.TWOSIDEDLIGHTING = false;
  45656. }
  45657. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45658. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45659. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45660. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45661. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45662. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45663. }
  45664. if (defines._areImageProcessingDirty) {
  45665. this._imageProcessingConfiguration.prepareDefines(defines);
  45666. }
  45667. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45668. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45669. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45670. // Misc.
  45671. if (defines._areMiscDirty) {
  45672. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45673. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45674. }
  45675. // Values that need to be evaluated on every frame
  45676. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45677. // Attribs
  45678. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45679. };
  45680. /**
  45681. * Force shader compilation
  45682. */
  45683. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45684. var _this = this;
  45685. var localOptions = __assign({ clipPlane: false }, options);
  45686. var defines = new PBRMaterialDefines();
  45687. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45688. if (effect.isReady()) {
  45689. if (onCompiled) {
  45690. onCompiled(this);
  45691. }
  45692. }
  45693. else {
  45694. effect.onCompileObservable.add(function () {
  45695. if (onCompiled) {
  45696. onCompiled(_this);
  45697. }
  45698. });
  45699. }
  45700. };
  45701. /**
  45702. * Initializes the uniform buffer layout for the shader.
  45703. */
  45704. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45705. // Order is important !
  45706. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45707. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45708. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45709. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45710. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45711. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45712. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45713. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45714. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45715. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45716. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45717. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45718. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45719. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45720. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45721. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45722. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45723. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45724. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45725. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45726. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45727. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45728. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45729. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45730. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45731. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45732. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45733. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45734. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45735. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45736. this._uniformBuffer.addUniform("pointSize", 1);
  45737. this._uniformBuffer.create();
  45738. };
  45739. /**
  45740. * Unbinds the textures.
  45741. */
  45742. PBRBaseMaterial.prototype.unbind = function () {
  45743. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45744. this._uniformBuffer.setTexture("reflectionSampler", null);
  45745. }
  45746. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45747. this._uniformBuffer.setTexture("refractionSampler", null);
  45748. }
  45749. _super.prototype.unbind.call(this);
  45750. };
  45751. /**
  45752. * Binds the submesh data.
  45753. * @param world - The world matrix.
  45754. * @param mesh - The BJS mesh.
  45755. * @param subMesh - A submesh of the BJS mesh.
  45756. */
  45757. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45758. var scene = this.getScene();
  45759. var defines = subMesh._materialDefines;
  45760. if (!defines) {
  45761. return;
  45762. }
  45763. var effect = subMesh.effect;
  45764. if (!effect) {
  45765. return;
  45766. }
  45767. this._activeEffect = effect;
  45768. // Matrices
  45769. this.bindOnlyWorldMatrix(world);
  45770. // Normal Matrix
  45771. if (defines.OBJECTSPACE_NORMALMAP) {
  45772. world.toNormalMatrix(this._normalMatrix);
  45773. this.bindOnlyNormalMatrix(this._normalMatrix);
  45774. }
  45775. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45776. // Bones
  45777. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45778. var reflectionTexture = null;
  45779. if (mustRebind) {
  45780. this._uniformBuffer.bindToEffect(effect, "Material");
  45781. this.bindViewProjection(effect);
  45782. reflectionTexture = this._getReflectionTexture();
  45783. var refractionTexture = this._getRefractionTexture();
  45784. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45785. // Texture uniforms
  45786. if (scene.texturesEnabled) {
  45787. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45788. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45789. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45790. }
  45791. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45792. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45793. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45794. }
  45795. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45796. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45797. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45798. }
  45799. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45800. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45801. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45802. if (reflectionTexture.boundingBoxSize) {
  45803. var cubeTexture = reflectionTexture;
  45804. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45805. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45806. }
  45807. var polynomials = reflectionTexture.sphericalPolynomial;
  45808. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45809. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45810. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45811. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45812. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45813. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45814. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45815. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45816. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45817. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45818. }
  45819. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45820. }
  45821. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45822. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45823. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45824. }
  45825. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45826. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45827. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45828. }
  45829. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45830. if (this._metallicTexture) {
  45831. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45832. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45833. }
  45834. else if (this._reflectivityTexture) {
  45835. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45836. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45837. }
  45838. if (this._microSurfaceTexture) {
  45839. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45840. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45841. }
  45842. }
  45843. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45844. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45845. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45846. if (scene._mirroredCameraPosition) {
  45847. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45848. }
  45849. else {
  45850. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45851. }
  45852. }
  45853. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45854. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45855. var depth = 1.0;
  45856. if (!refractionTexture.isCube) {
  45857. if (refractionTexture.depth) {
  45858. depth = refractionTexture.depth;
  45859. }
  45860. }
  45861. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45862. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45863. }
  45864. }
  45865. // Point size
  45866. if (this.pointsCloud) {
  45867. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45868. }
  45869. // Colors
  45870. if (defines.METALLICWORKFLOW) {
  45871. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45872. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45873. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45874. }
  45875. else {
  45876. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45877. }
  45878. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45879. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45880. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45881. // Misc
  45882. this._lightingInfos.x = this._directIntensity;
  45883. this._lightingInfos.y = this._emissiveIntensity;
  45884. this._lightingInfos.z = this._environmentIntensity;
  45885. this._lightingInfos.w = this._specularIntensity;
  45886. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45887. }
  45888. // Textures
  45889. if (scene.texturesEnabled) {
  45890. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45891. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45892. }
  45893. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45894. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45895. }
  45896. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45897. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45898. }
  45899. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45900. if (defines.LODBASEDMICROSFURACE) {
  45901. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45902. }
  45903. else {
  45904. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45905. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45906. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45907. }
  45908. }
  45909. if (defines.ENVIRONMENTBRDF) {
  45910. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45911. }
  45912. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45913. if (defines.LODBASEDMICROSFURACE) {
  45914. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45915. }
  45916. else {
  45917. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45918. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45919. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45920. }
  45921. }
  45922. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45923. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45924. }
  45925. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45926. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45927. }
  45928. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45929. if (this._metallicTexture) {
  45930. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45931. }
  45932. else if (this._reflectivityTexture) {
  45933. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45934. }
  45935. if (this._microSurfaceTexture) {
  45936. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45937. }
  45938. }
  45939. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45940. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45941. }
  45942. }
  45943. // Clip plane
  45944. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45945. // Colors
  45946. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45947. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45948. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45949. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45950. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45951. }
  45952. if (mustRebind || !this.isFrozen) {
  45953. // Lights
  45954. if (scene.lightsEnabled && !this._disableLighting) {
  45955. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45956. }
  45957. // View
  45958. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45959. this.bindView(effect);
  45960. }
  45961. // Fog
  45962. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45963. // Morph targets
  45964. if (defines.NUM_MORPH_INFLUENCERS) {
  45965. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45966. }
  45967. // image processing
  45968. this._imageProcessingConfiguration.bind(this._activeEffect);
  45969. // Log. depth
  45970. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45971. }
  45972. this._uniformBuffer.update();
  45973. this._afterBind(mesh, this._activeEffect);
  45974. };
  45975. /**
  45976. * Returns the animatable textures.
  45977. * @returns - Array of animatable textures.
  45978. */
  45979. PBRBaseMaterial.prototype.getAnimatables = function () {
  45980. var results = [];
  45981. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45982. results.push(this._albedoTexture);
  45983. }
  45984. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45985. results.push(this._ambientTexture);
  45986. }
  45987. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45988. results.push(this._opacityTexture);
  45989. }
  45990. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45991. results.push(this._reflectionTexture);
  45992. }
  45993. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45994. results.push(this._emissiveTexture);
  45995. }
  45996. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45997. results.push(this._metallicTexture);
  45998. }
  45999. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46000. results.push(this._reflectivityTexture);
  46001. }
  46002. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46003. results.push(this._bumpTexture);
  46004. }
  46005. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46006. results.push(this._lightmapTexture);
  46007. }
  46008. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46009. results.push(this._refractionTexture);
  46010. }
  46011. return results;
  46012. };
  46013. /**
  46014. * Returns the texture used for reflections.
  46015. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46016. */
  46017. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46018. if (this._reflectionTexture) {
  46019. return this._reflectionTexture;
  46020. }
  46021. return this.getScene().environmentTexture;
  46022. };
  46023. /**
  46024. * Returns the texture used for refraction or null if none is used.
  46025. * @returns - Refection texture if present. If no refraction texture and refraction
  46026. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46027. */
  46028. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46029. if (this._refractionTexture) {
  46030. return this._refractionTexture;
  46031. }
  46032. if (this._linkRefractionWithTransparency) {
  46033. return this.getScene().environmentTexture;
  46034. }
  46035. return null;
  46036. };
  46037. /**
  46038. * Disposes the resources of the material.
  46039. * @param forceDisposeEffect - Forces the disposal of effects.
  46040. * @param forceDisposeTextures - Forces the disposal of all textures.
  46041. */
  46042. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46043. if (forceDisposeTextures) {
  46044. if (this._albedoTexture) {
  46045. this._albedoTexture.dispose();
  46046. }
  46047. if (this._ambientTexture) {
  46048. this._ambientTexture.dispose();
  46049. }
  46050. if (this._opacityTexture) {
  46051. this._opacityTexture.dispose();
  46052. }
  46053. if (this._reflectionTexture) {
  46054. this._reflectionTexture.dispose();
  46055. }
  46056. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46057. this._environmentBRDFTexture.dispose();
  46058. }
  46059. if (this._emissiveTexture) {
  46060. this._emissiveTexture.dispose();
  46061. }
  46062. if (this._metallicTexture) {
  46063. this._metallicTexture.dispose();
  46064. }
  46065. if (this._reflectivityTexture) {
  46066. this._reflectivityTexture.dispose();
  46067. }
  46068. if (this._bumpTexture) {
  46069. this._bumpTexture.dispose();
  46070. }
  46071. if (this._lightmapTexture) {
  46072. this._lightmapTexture.dispose();
  46073. }
  46074. if (this._refractionTexture) {
  46075. this._refractionTexture.dispose();
  46076. }
  46077. }
  46078. this._renderTargets.dispose();
  46079. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46080. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46081. }
  46082. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46083. };
  46084. /**
  46085. * Stores the reflectivity values based on metallic roughness workflow.
  46086. */
  46087. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46088. __decorate([
  46089. BABYLON.serializeAsImageProcessingConfiguration()
  46090. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46091. __decorate([
  46092. BABYLON.serialize()
  46093. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46094. __decorate([
  46095. BABYLON.serialize()
  46096. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46097. return PBRBaseMaterial;
  46098. }(BABYLON.PushMaterial));
  46099. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46100. })(BABYLON || (BABYLON = {}));
  46101. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46102. var BABYLON;
  46103. (function (BABYLON) {
  46104. /**
  46105. * The Physically based simple base material of BJS.
  46106. *
  46107. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46108. * It is used as the base class for both the specGloss and metalRough conventions.
  46109. */
  46110. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46111. __extends(PBRBaseSimpleMaterial, _super);
  46112. /**
  46113. * Instantiates a new PBRMaterial instance.
  46114. *
  46115. * @param name The material name
  46116. * @param scene The scene the material will be use in.
  46117. */
  46118. function PBRBaseSimpleMaterial(name, scene) {
  46119. var _this = _super.call(this, name, scene) || this;
  46120. /**
  46121. * Number of Simultaneous lights allowed on the material.
  46122. */
  46123. _this.maxSimultaneousLights = 4;
  46124. /**
  46125. * If sets to true, disables all the lights affecting the material.
  46126. */
  46127. _this.disableLighting = false;
  46128. /**
  46129. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46130. */
  46131. _this.invertNormalMapX = false;
  46132. /**
  46133. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46134. */
  46135. _this.invertNormalMapY = false;
  46136. /**
  46137. * Emissivie color used to self-illuminate the model.
  46138. */
  46139. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46140. /**
  46141. * Occlusion Channel Strenght.
  46142. */
  46143. _this.occlusionStrength = 1.0;
  46144. _this.useLightmapAsShadowmap = false;
  46145. _this._useAlphaFromAlbedoTexture = true;
  46146. _this._useAmbientInGrayScale = true;
  46147. return _this;
  46148. }
  46149. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46150. /**
  46151. * Gets the current double sided mode.
  46152. */
  46153. get: function () {
  46154. return this._twoSidedLighting;
  46155. },
  46156. /**
  46157. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46158. */
  46159. set: function (value) {
  46160. if (this._twoSidedLighting === value) {
  46161. return;
  46162. }
  46163. this._twoSidedLighting = value;
  46164. this.backFaceCulling = !value;
  46165. this._markAllSubMeshesAsTexturesDirty();
  46166. },
  46167. enumerable: true,
  46168. configurable: true
  46169. });
  46170. /**
  46171. * Return the active textures of the material.
  46172. */
  46173. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46174. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46175. if (this.environmentTexture) {
  46176. activeTextures.push(this.environmentTexture);
  46177. }
  46178. if (this.normalTexture) {
  46179. activeTextures.push(this.normalTexture);
  46180. }
  46181. if (this.emissiveTexture) {
  46182. activeTextures.push(this.emissiveTexture);
  46183. }
  46184. if (this.occlusionTexture) {
  46185. activeTextures.push(this.occlusionTexture);
  46186. }
  46187. if (this.lightmapTexture) {
  46188. activeTextures.push(this.lightmapTexture);
  46189. }
  46190. return activeTextures;
  46191. };
  46192. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46193. if (_super.prototype.hasTexture.call(this, texture)) {
  46194. return true;
  46195. }
  46196. if (this.lightmapTexture === texture) {
  46197. return true;
  46198. }
  46199. return false;
  46200. };
  46201. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46202. return "PBRBaseSimpleMaterial";
  46203. };
  46204. __decorate([
  46205. BABYLON.serialize(),
  46206. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46207. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46208. __decorate([
  46209. BABYLON.serialize(),
  46210. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46211. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46212. __decorate([
  46213. BABYLON.serializeAsTexture(),
  46214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46215. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46216. __decorate([
  46217. BABYLON.serialize(),
  46218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46219. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46220. __decorate([
  46221. BABYLON.serialize(),
  46222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46223. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46224. __decorate([
  46225. BABYLON.serializeAsTexture(),
  46226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46227. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46228. __decorate([
  46229. BABYLON.serializeAsColor3("emissive"),
  46230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46231. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46232. __decorate([
  46233. BABYLON.serializeAsTexture(),
  46234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46235. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46236. __decorate([
  46237. BABYLON.serialize(),
  46238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46239. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46240. __decorate([
  46241. BABYLON.serializeAsTexture(),
  46242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46243. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46244. __decorate([
  46245. BABYLON.serialize(),
  46246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46247. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46248. __decorate([
  46249. BABYLON.serialize()
  46250. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46251. __decorate([
  46252. BABYLON.serializeAsTexture(),
  46253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46254. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46255. __decorate([
  46256. BABYLON.serialize(),
  46257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46258. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46259. return PBRBaseSimpleMaterial;
  46260. }(BABYLON.PBRBaseMaterial));
  46261. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46262. })(BABYLON || (BABYLON = {}));
  46263. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46264. var BABYLON;
  46265. (function (BABYLON) {
  46266. /**
  46267. * The Physically based material of BJS.
  46268. *
  46269. * This offers the main features of a standard PBR material.
  46270. * For more information, please refer to the documentation :
  46271. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46272. */
  46273. var PBRMaterial = /** @class */ (function (_super) {
  46274. __extends(PBRMaterial, _super);
  46275. /**
  46276. * Instantiates a new PBRMaterial instance.
  46277. *
  46278. * @param name The material name
  46279. * @param scene The scene the material will be use in.
  46280. */
  46281. function PBRMaterial(name, scene) {
  46282. var _this = _super.call(this, name, scene) || this;
  46283. /**
  46284. * Intensity of the direct lights e.g. the four lights available in your scene.
  46285. * This impacts both the direct diffuse and specular highlights.
  46286. */
  46287. _this.directIntensity = 1.0;
  46288. /**
  46289. * Intensity of the emissive part of the material.
  46290. * This helps controlling the emissive effect without modifying the emissive color.
  46291. */
  46292. _this.emissiveIntensity = 1.0;
  46293. /**
  46294. * Intensity of the environment e.g. how much the environment will light the object
  46295. * either through harmonics for rough material or through the refelction for shiny ones.
  46296. */
  46297. _this.environmentIntensity = 1.0;
  46298. /**
  46299. * This is a special control allowing the reduction of the specular highlights coming from the
  46300. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46301. */
  46302. _this.specularIntensity = 1.0;
  46303. /**
  46304. * Debug Control allowing disabling the bump map on this material.
  46305. */
  46306. _this.disableBumpMap = false;
  46307. /**
  46308. * AKA Occlusion Texture Intensity in other nomenclature.
  46309. */
  46310. _this.ambientTextureStrength = 1.0;
  46311. /**
  46312. * The color of a material in ambient lighting.
  46313. */
  46314. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46315. /**
  46316. * AKA Diffuse Color in other nomenclature.
  46317. */
  46318. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46319. /**
  46320. * AKA Specular Color in other nomenclature.
  46321. */
  46322. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46323. /**
  46324. * The color reflected from the material.
  46325. */
  46326. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46327. /**
  46328. * The color emitted from the material.
  46329. */
  46330. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46331. /**
  46332. * AKA Glossiness in other nomenclature.
  46333. */
  46334. _this.microSurface = 1.0;
  46335. /**
  46336. * source material index of refraction (IOR)' / 'destination material IOR.
  46337. */
  46338. _this.indexOfRefraction = 0.66;
  46339. /**
  46340. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46341. */
  46342. _this.invertRefractionY = false;
  46343. /**
  46344. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46345. * Materials half opaque for instance using refraction could benefit from this control.
  46346. */
  46347. _this.linkRefractionWithTransparency = false;
  46348. _this.useLightmapAsShadowmap = false;
  46349. /**
  46350. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46351. */
  46352. _this.useAlphaFromAlbedoTexture = false;
  46353. /**
  46354. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46355. */
  46356. _this.forceAlphaTest = false;
  46357. /**
  46358. * Defines the alpha limits in alpha test mode.
  46359. */
  46360. _this.alphaCutOff = 0.4;
  46361. /**
  46362. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46363. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46364. */
  46365. _this.useSpecularOverAlpha = true;
  46366. /**
  46367. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46368. */
  46369. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46370. /**
  46371. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46372. */
  46373. _this.useRoughnessFromMetallicTextureAlpha = true;
  46374. /**
  46375. * Specifies if the metallic texture contains the roughness information in its green channel.
  46376. */
  46377. _this.useRoughnessFromMetallicTextureGreen = false;
  46378. /**
  46379. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46380. */
  46381. _this.useMetallnessFromMetallicTextureBlue = false;
  46382. /**
  46383. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46384. */
  46385. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46386. /**
  46387. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46388. */
  46389. _this.useAmbientInGrayScale = false;
  46390. /**
  46391. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46392. * The material will try to infer what glossiness each pixel should be.
  46393. */
  46394. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46395. /**
  46396. * BJS is using an harcoded light falloff based on a manually sets up range.
  46397. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46398. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46399. */
  46400. _this.usePhysicalLightFalloff = true;
  46401. /**
  46402. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46403. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46404. */
  46405. _this.useRadianceOverAlpha = true;
  46406. /**
  46407. * Allows using an object space normal map (instead of tangent space).
  46408. */
  46409. _this.useObjectSpaceNormalMap = false;
  46410. /**
  46411. * Allows using the bump map in parallax mode.
  46412. */
  46413. _this.useParallax = false;
  46414. /**
  46415. * Allows using the bump map in parallax occlusion mode.
  46416. */
  46417. _this.useParallaxOcclusion = false;
  46418. /**
  46419. * Controls the scale bias of the parallax mode.
  46420. */
  46421. _this.parallaxScaleBias = 0.05;
  46422. /**
  46423. * If sets to true, disables all the lights affecting the material.
  46424. */
  46425. _this.disableLighting = false;
  46426. /**
  46427. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46428. */
  46429. _this.forceIrradianceInFragment = false;
  46430. /**
  46431. * Number of Simultaneous lights allowed on the material.
  46432. */
  46433. _this.maxSimultaneousLights = 4;
  46434. /**
  46435. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46436. */
  46437. _this.invertNormalMapX = false;
  46438. /**
  46439. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46440. */
  46441. _this.invertNormalMapY = false;
  46442. /**
  46443. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46444. */
  46445. _this.twoSidedLighting = false;
  46446. /**
  46447. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46448. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46449. */
  46450. _this.useAlphaFresnel = false;
  46451. /**
  46452. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46453. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46454. */
  46455. _this.useLinearAlphaFresnel = false;
  46456. /**
  46457. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46458. * And/Or occlude the blended part.
  46459. */
  46460. _this.environmentBRDFTexture = null;
  46461. /**
  46462. * Force normal to face away from face.
  46463. */
  46464. _this.forceNormalForward = false;
  46465. /**
  46466. * Enables specular anti aliasing in the PBR shader.
  46467. * It will both interacts on the Geometry for analytical and IBL lighting.
  46468. * It also prefilter the roughness map based on the bump values.
  46469. */
  46470. _this.enableSpecularAntiAliasing = false;
  46471. /**
  46472. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46473. * makes the reflect vector face the model (under horizon).
  46474. */
  46475. _this.useHorizonOcclusion = true;
  46476. /**
  46477. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46478. * too much the area relying on ambient texture to define their ambient occlusion.
  46479. */
  46480. _this.useRadianceOcclusion = true;
  46481. /**
  46482. * If set to true, no lighting calculations will be applied.
  46483. */
  46484. _this.unlit = false;
  46485. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46486. return _this;
  46487. }
  46488. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46489. /**
  46490. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46491. */
  46492. get: function () {
  46493. return this._PBRMATERIAL_OPAQUE;
  46494. },
  46495. enumerable: true,
  46496. configurable: true
  46497. });
  46498. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46499. /**
  46500. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46501. */
  46502. get: function () {
  46503. return this._PBRMATERIAL_ALPHATEST;
  46504. },
  46505. enumerable: true,
  46506. configurable: true
  46507. });
  46508. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46509. /**
  46510. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46511. */
  46512. get: function () {
  46513. return this._PBRMATERIAL_ALPHABLEND;
  46514. },
  46515. enumerable: true,
  46516. configurable: true
  46517. });
  46518. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46519. /**
  46520. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46521. * They are also discarded below the alpha cutoff threshold to improve performances.
  46522. */
  46523. get: function () {
  46524. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46525. },
  46526. enumerable: true,
  46527. configurable: true
  46528. });
  46529. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46530. /**
  46531. * Gets the image processing configuration used either in this material.
  46532. */
  46533. get: function () {
  46534. return this._imageProcessingConfiguration;
  46535. },
  46536. /**
  46537. * Sets the Default image processing configuration used either in the this material.
  46538. *
  46539. * If sets to null, the scene one is in use.
  46540. */
  46541. set: function (value) {
  46542. this._attachImageProcessingConfiguration(value);
  46543. // Ensure the effect will be rebuilt.
  46544. this._markAllSubMeshesAsTexturesDirty();
  46545. },
  46546. enumerable: true,
  46547. configurable: true
  46548. });
  46549. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46550. /**
  46551. * Gets wether the color curves effect is enabled.
  46552. */
  46553. get: function () {
  46554. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46555. },
  46556. /**
  46557. * Sets wether the color curves effect is enabled.
  46558. */
  46559. set: function (value) {
  46560. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46561. },
  46562. enumerable: true,
  46563. configurable: true
  46564. });
  46565. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46566. /**
  46567. * Gets wether the color grading effect is enabled.
  46568. */
  46569. get: function () {
  46570. return this.imageProcessingConfiguration.colorGradingEnabled;
  46571. },
  46572. /**
  46573. * Gets wether the color grading effect is enabled.
  46574. */
  46575. set: function (value) {
  46576. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46577. },
  46578. enumerable: true,
  46579. configurable: true
  46580. });
  46581. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46582. /**
  46583. * Gets wether tonemapping is enabled or not.
  46584. */
  46585. get: function () {
  46586. return this._imageProcessingConfiguration.toneMappingEnabled;
  46587. },
  46588. /**
  46589. * Sets wether tonemapping is enabled or not
  46590. */
  46591. set: function (value) {
  46592. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46593. },
  46594. enumerable: true,
  46595. configurable: true
  46596. });
  46597. ;
  46598. ;
  46599. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46600. /**
  46601. * The camera exposure used on this material.
  46602. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46603. * This corresponds to a photographic exposure.
  46604. */
  46605. get: function () {
  46606. return this._imageProcessingConfiguration.exposure;
  46607. },
  46608. /**
  46609. * The camera exposure used on this material.
  46610. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46611. * This corresponds to a photographic exposure.
  46612. */
  46613. set: function (value) {
  46614. this._imageProcessingConfiguration.exposure = value;
  46615. },
  46616. enumerable: true,
  46617. configurable: true
  46618. });
  46619. ;
  46620. ;
  46621. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46622. /**
  46623. * Gets The camera contrast used on this material.
  46624. */
  46625. get: function () {
  46626. return this._imageProcessingConfiguration.contrast;
  46627. },
  46628. /**
  46629. * Sets The camera contrast used on this material.
  46630. */
  46631. set: function (value) {
  46632. this._imageProcessingConfiguration.contrast = value;
  46633. },
  46634. enumerable: true,
  46635. configurable: true
  46636. });
  46637. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46638. /**
  46639. * Gets the Color Grading 2D Lookup Texture.
  46640. */
  46641. get: function () {
  46642. return this._imageProcessingConfiguration.colorGradingTexture;
  46643. },
  46644. /**
  46645. * Sets the Color Grading 2D Lookup Texture.
  46646. */
  46647. set: function (value) {
  46648. this._imageProcessingConfiguration.colorGradingTexture = value;
  46649. },
  46650. enumerable: true,
  46651. configurable: true
  46652. });
  46653. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46654. /**
  46655. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46656. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46657. * 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;
  46658. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46659. */
  46660. get: function () {
  46661. return this._imageProcessingConfiguration.colorCurves;
  46662. },
  46663. /**
  46664. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46665. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46666. * 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;
  46667. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46668. */
  46669. set: function (value) {
  46670. this._imageProcessingConfiguration.colorCurves = value;
  46671. },
  46672. enumerable: true,
  46673. configurable: true
  46674. });
  46675. /**
  46676. * Returns the name of this material class.
  46677. */
  46678. PBRMaterial.prototype.getClassName = function () {
  46679. return "PBRMaterial";
  46680. };
  46681. /**
  46682. * Returns an array of the actively used textures.
  46683. * @returns - Array of BaseTextures
  46684. */
  46685. PBRMaterial.prototype.getActiveTextures = function () {
  46686. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46687. if (this._albedoTexture) {
  46688. activeTextures.push(this._albedoTexture);
  46689. }
  46690. if (this._ambientTexture) {
  46691. activeTextures.push(this._ambientTexture);
  46692. }
  46693. if (this._opacityTexture) {
  46694. activeTextures.push(this._opacityTexture);
  46695. }
  46696. if (this._reflectionTexture) {
  46697. activeTextures.push(this._reflectionTexture);
  46698. }
  46699. if (this._emissiveTexture) {
  46700. activeTextures.push(this._emissiveTexture);
  46701. }
  46702. if (this._reflectivityTexture) {
  46703. activeTextures.push(this._reflectivityTexture);
  46704. }
  46705. if (this._metallicTexture) {
  46706. activeTextures.push(this._metallicTexture);
  46707. }
  46708. if (this._microSurfaceTexture) {
  46709. activeTextures.push(this._microSurfaceTexture);
  46710. }
  46711. if (this._bumpTexture) {
  46712. activeTextures.push(this._bumpTexture);
  46713. }
  46714. if (this._lightmapTexture) {
  46715. activeTextures.push(this._lightmapTexture);
  46716. }
  46717. if (this._refractionTexture) {
  46718. activeTextures.push(this._refractionTexture);
  46719. }
  46720. return activeTextures;
  46721. };
  46722. /**
  46723. * Checks to see if a texture is used in the material.
  46724. * @param texture - Base texture to use.
  46725. * @returns - Boolean specifying if a texture is used in the material.
  46726. */
  46727. PBRMaterial.prototype.hasTexture = function (texture) {
  46728. if (_super.prototype.hasTexture.call(this, texture)) {
  46729. return true;
  46730. }
  46731. if (this._albedoTexture === texture) {
  46732. return true;
  46733. }
  46734. if (this._ambientTexture === texture) {
  46735. return true;
  46736. }
  46737. if (this._opacityTexture === texture) {
  46738. return true;
  46739. }
  46740. if (this._reflectionTexture === texture) {
  46741. return true;
  46742. }
  46743. if (this._reflectivityTexture === texture) {
  46744. return true;
  46745. }
  46746. if (this._metallicTexture === texture) {
  46747. return true;
  46748. }
  46749. if (this._microSurfaceTexture === texture) {
  46750. return true;
  46751. }
  46752. if (this._bumpTexture === texture) {
  46753. return true;
  46754. }
  46755. if (this._lightmapTexture === texture) {
  46756. return true;
  46757. }
  46758. if (this._refractionTexture === texture) {
  46759. return true;
  46760. }
  46761. return false;
  46762. };
  46763. /**
  46764. * Makes a duplicate of the current material.
  46765. * @param name - name to use for the new material.
  46766. */
  46767. PBRMaterial.prototype.clone = function (name) {
  46768. var _this = this;
  46769. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46770. clone.id = name;
  46771. clone.name = name;
  46772. return clone;
  46773. };
  46774. /**
  46775. * Serializes this PBR Material.
  46776. * @returns - An object with the serialized material.
  46777. */
  46778. PBRMaterial.prototype.serialize = function () {
  46779. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46780. serializationObject.customType = "BABYLON.PBRMaterial";
  46781. return serializationObject;
  46782. };
  46783. // Statics
  46784. /**
  46785. * Parses a PBR Material from a serialized object.
  46786. * @param source - Serialized object.
  46787. * @param scene - BJS scene instance.
  46788. * @param rootUrl - url for the scene object
  46789. * @returns - PBRMaterial
  46790. */
  46791. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46792. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46793. };
  46794. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46795. /**
  46796. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46797. */
  46798. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46799. /**
  46800. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46801. */
  46802. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46803. /**
  46804. * 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.
  46805. * They are also discarded below the alpha cutoff threshold to improve performances.
  46806. */
  46807. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46808. __decorate([
  46809. BABYLON.serialize(),
  46810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46811. ], PBRMaterial.prototype, "directIntensity", void 0);
  46812. __decorate([
  46813. BABYLON.serialize(),
  46814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46815. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46816. __decorate([
  46817. BABYLON.serialize(),
  46818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46819. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46820. __decorate([
  46821. BABYLON.serialize(),
  46822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46823. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46824. __decorate([
  46825. BABYLON.serialize(),
  46826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46827. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46828. __decorate([
  46829. BABYLON.serializeAsTexture(),
  46830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46831. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46832. __decorate([
  46833. BABYLON.serializeAsTexture(),
  46834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46835. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46836. __decorate([
  46837. BABYLON.serialize(),
  46838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46839. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46840. __decorate([
  46841. BABYLON.serializeAsTexture(),
  46842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46843. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46844. __decorate([
  46845. BABYLON.serializeAsTexture(),
  46846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46847. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46848. __decorate([
  46849. BABYLON.serializeAsTexture(),
  46850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46851. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46852. __decorate([
  46853. BABYLON.serializeAsTexture(),
  46854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46855. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46856. __decorate([
  46857. BABYLON.serializeAsTexture(),
  46858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46859. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46860. __decorate([
  46861. BABYLON.serialize(),
  46862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46863. ], PBRMaterial.prototype, "metallic", void 0);
  46864. __decorate([
  46865. BABYLON.serialize(),
  46866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46867. ], PBRMaterial.prototype, "roughness", void 0);
  46868. __decorate([
  46869. BABYLON.serializeAsTexture(),
  46870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46871. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46872. __decorate([
  46873. BABYLON.serializeAsTexture(),
  46874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46875. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46876. __decorate([
  46877. BABYLON.serializeAsTexture(),
  46878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46879. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46880. __decorate([
  46881. BABYLON.serializeAsTexture(),
  46882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46883. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46884. __decorate([
  46885. BABYLON.serializeAsColor3("ambient"),
  46886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46887. ], PBRMaterial.prototype, "ambientColor", void 0);
  46888. __decorate([
  46889. BABYLON.serializeAsColor3("albedo"),
  46890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46891. ], PBRMaterial.prototype, "albedoColor", void 0);
  46892. __decorate([
  46893. BABYLON.serializeAsColor3("reflectivity"),
  46894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46895. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46896. __decorate([
  46897. BABYLON.serializeAsColor3("reflection"),
  46898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46899. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46900. __decorate([
  46901. BABYLON.serializeAsColor3("emissive"),
  46902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46903. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46904. __decorate([
  46905. BABYLON.serialize(),
  46906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46907. ], PBRMaterial.prototype, "microSurface", void 0);
  46908. __decorate([
  46909. BABYLON.serialize(),
  46910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46911. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46912. __decorate([
  46913. BABYLON.serialize(),
  46914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46915. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46916. __decorate([
  46917. BABYLON.serialize(),
  46918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46919. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46920. __decorate([
  46921. BABYLON.serialize(),
  46922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46923. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46924. __decorate([
  46925. BABYLON.serialize(),
  46926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46927. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46928. __decorate([
  46929. BABYLON.serialize(),
  46930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46931. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46932. __decorate([
  46933. BABYLON.serialize(),
  46934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46935. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46936. __decorate([
  46937. BABYLON.serialize(),
  46938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46939. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46940. __decorate([
  46941. BABYLON.serialize(),
  46942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46943. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46944. __decorate([
  46945. BABYLON.serialize(),
  46946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46947. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46948. __decorate([
  46949. BABYLON.serialize(),
  46950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46951. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46952. __decorate([
  46953. BABYLON.serialize(),
  46954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46955. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46956. __decorate([
  46957. BABYLON.serialize(),
  46958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46959. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46960. __decorate([
  46961. BABYLON.serialize(),
  46962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46963. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46964. __decorate([
  46965. BABYLON.serialize(),
  46966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46967. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46968. __decorate([
  46969. BABYLON.serialize(),
  46970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46971. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46972. __decorate([
  46973. BABYLON.serialize(),
  46974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46975. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46976. __decorate([
  46977. BABYLON.serialize(),
  46978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46979. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46980. __decorate([
  46981. BABYLON.serialize(),
  46982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46983. ], PBRMaterial.prototype, "useParallax", void 0);
  46984. __decorate([
  46985. BABYLON.serialize(),
  46986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46987. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46988. __decorate([
  46989. BABYLON.serialize(),
  46990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46991. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46992. __decorate([
  46993. BABYLON.serialize(),
  46994. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46995. ], PBRMaterial.prototype, "disableLighting", void 0);
  46996. __decorate([
  46997. BABYLON.serialize(),
  46998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46999. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47000. __decorate([
  47001. BABYLON.serialize(),
  47002. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47003. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47004. __decorate([
  47005. BABYLON.serialize(),
  47006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47007. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47008. __decorate([
  47009. BABYLON.serialize(),
  47010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47011. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47012. __decorate([
  47013. BABYLON.serialize(),
  47014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47015. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47016. __decorate([
  47017. BABYLON.serialize(),
  47018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47019. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47020. __decorate([
  47021. BABYLON.serialize(),
  47022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47023. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47024. __decorate([
  47025. BABYLON.serializeAsTexture(),
  47026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47027. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47028. __decorate([
  47029. BABYLON.serialize(),
  47030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47031. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47032. __decorate([
  47033. BABYLON.serialize(),
  47034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47035. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47036. __decorate([
  47037. BABYLON.serialize(),
  47038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47039. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47040. __decorate([
  47041. BABYLON.serialize(),
  47042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47043. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47044. __decorate([
  47045. BABYLON.serialize(),
  47046. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47047. ], PBRMaterial.prototype, "unlit", void 0);
  47048. return PBRMaterial;
  47049. }(BABYLON.PBRBaseMaterial));
  47050. BABYLON.PBRMaterial = PBRMaterial;
  47051. })(BABYLON || (BABYLON = {}));
  47052. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47053. var BABYLON;
  47054. (function (BABYLON) {
  47055. /**
  47056. * The PBR material of BJS following the metal roughness convention.
  47057. *
  47058. * This fits to the PBR convention in the GLTF definition:
  47059. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47060. */
  47061. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47062. __extends(PBRMetallicRoughnessMaterial, _super);
  47063. /**
  47064. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47065. *
  47066. * @param name The material name
  47067. * @param scene The scene the material will be use in.
  47068. */
  47069. function PBRMetallicRoughnessMaterial(name, scene) {
  47070. var _this = _super.call(this, name, scene) || this;
  47071. _this._useRoughnessFromMetallicTextureAlpha = false;
  47072. _this._useRoughnessFromMetallicTextureGreen = true;
  47073. _this._useMetallnessFromMetallicTextureBlue = true;
  47074. _this.metallic = 1.0;
  47075. _this.roughness = 1.0;
  47076. return _this;
  47077. }
  47078. /**
  47079. * Return the currrent class name of the material.
  47080. */
  47081. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47082. return "PBRMetallicRoughnessMaterial";
  47083. };
  47084. /**
  47085. * Return the active textures of the material.
  47086. */
  47087. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47088. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47089. if (this.baseTexture) {
  47090. activeTextures.push(this.baseTexture);
  47091. }
  47092. if (this.metallicRoughnessTexture) {
  47093. activeTextures.push(this.metallicRoughnessTexture);
  47094. }
  47095. return activeTextures;
  47096. };
  47097. /**
  47098. * Checks to see if a texture is used in the material.
  47099. * @param texture - Base texture to use.
  47100. * @returns - Boolean specifying if a texture is used in the material.
  47101. */
  47102. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47103. if (_super.prototype.hasTexture.call(this, texture)) {
  47104. return true;
  47105. }
  47106. if (this.baseTexture === texture) {
  47107. return true;
  47108. }
  47109. if (this.metallicRoughnessTexture === texture) {
  47110. return true;
  47111. }
  47112. return false;
  47113. };
  47114. /**
  47115. * Makes a duplicate of the current material.
  47116. * @param name - name to use for the new material.
  47117. */
  47118. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47119. var _this = this;
  47120. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47121. clone.id = name;
  47122. clone.name = name;
  47123. return clone;
  47124. };
  47125. /**
  47126. * Serialize the material to a parsable JSON object.
  47127. */
  47128. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47129. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47130. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47131. return serializationObject;
  47132. };
  47133. /**
  47134. * Parses a JSON object correponding to the serialize function.
  47135. */
  47136. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47137. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47138. };
  47139. __decorate([
  47140. BABYLON.serializeAsColor3(),
  47141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47142. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47143. __decorate([
  47144. BABYLON.serializeAsTexture(),
  47145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47146. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47147. __decorate([
  47148. BABYLON.serialize(),
  47149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47150. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47151. __decorate([
  47152. BABYLON.serialize(),
  47153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47154. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47155. __decorate([
  47156. BABYLON.serializeAsTexture(),
  47157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47158. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47159. return PBRMetallicRoughnessMaterial;
  47160. }(BABYLON.PBRBaseSimpleMaterial));
  47161. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47162. })(BABYLON || (BABYLON = {}));
  47163. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47164. var BABYLON;
  47165. (function (BABYLON) {
  47166. /**
  47167. * The PBR material of BJS following the specular glossiness convention.
  47168. *
  47169. * This fits to the PBR convention in the GLTF definition:
  47170. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47171. */
  47172. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47173. __extends(PBRSpecularGlossinessMaterial, _super);
  47174. /**
  47175. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47176. *
  47177. * @param name The material name
  47178. * @param scene The scene the material will be use in.
  47179. */
  47180. function PBRSpecularGlossinessMaterial(name, scene) {
  47181. var _this = _super.call(this, name, scene) || this;
  47182. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47183. return _this;
  47184. }
  47185. /**
  47186. * Return the currrent class name of the material.
  47187. */
  47188. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47189. return "PBRSpecularGlossinessMaterial";
  47190. };
  47191. /**
  47192. * Return the active textures of the material.
  47193. */
  47194. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47195. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47196. if (this.diffuseTexture) {
  47197. activeTextures.push(this.diffuseTexture);
  47198. }
  47199. if (this.specularGlossinessTexture) {
  47200. activeTextures.push(this.specularGlossinessTexture);
  47201. }
  47202. return activeTextures;
  47203. };
  47204. /**
  47205. * Checks to see if a texture is used in the material.
  47206. * @param texture - Base texture to use.
  47207. * @returns - Boolean specifying if a texture is used in the material.
  47208. */
  47209. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47210. if (_super.prototype.hasTexture.call(this, texture)) {
  47211. return true;
  47212. }
  47213. if (this.diffuseTexture === texture) {
  47214. return true;
  47215. }
  47216. if (this.specularGlossinessTexture === texture) {
  47217. return true;
  47218. }
  47219. return false;
  47220. };
  47221. /**
  47222. * Makes a duplicate of the current material.
  47223. * @param name - name to use for the new material.
  47224. */
  47225. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47226. var _this = this;
  47227. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47228. clone.id = name;
  47229. clone.name = name;
  47230. return clone;
  47231. };
  47232. /**
  47233. * Serialize the material to a parsable JSON object.
  47234. */
  47235. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47236. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47237. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47238. return serializationObject;
  47239. };
  47240. /**
  47241. * Parses a JSON object correponding to the serialize function.
  47242. */
  47243. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47244. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47245. };
  47246. __decorate([
  47247. BABYLON.serializeAsColor3("diffuse"),
  47248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47249. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47250. __decorate([
  47251. BABYLON.serializeAsTexture(),
  47252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47253. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47254. __decorate([
  47255. BABYLON.serializeAsColor3("specular"),
  47256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47257. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47258. __decorate([
  47259. BABYLON.serialize(),
  47260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47261. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47262. __decorate([
  47263. BABYLON.serializeAsTexture(),
  47264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47265. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47266. return PBRSpecularGlossinessMaterial;
  47267. }(BABYLON.PBRBaseSimpleMaterial));
  47268. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47269. })(BABYLON || (BABYLON = {}));
  47270. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47271. var BABYLON;
  47272. (function (BABYLON) {
  47273. BABYLON.CameraInputTypes = {};
  47274. var CameraInputsManager = /** @class */ (function () {
  47275. function CameraInputsManager(camera) {
  47276. this.attached = {};
  47277. this.camera = camera;
  47278. this.checkInputs = function () { };
  47279. }
  47280. /**
  47281. * Add an input method to a camera.
  47282. * builtin inputs example: camera.inputs.addGamepad();
  47283. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47284. * @param input camera input method
  47285. */
  47286. CameraInputsManager.prototype.add = function (input) {
  47287. var type = input.getSimpleName();
  47288. if (this.attached[type]) {
  47289. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47290. return;
  47291. }
  47292. this.attached[type] = input;
  47293. input.camera = this.camera;
  47294. //for checkInputs, we are dynamically creating a function
  47295. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47296. if (input.checkInputs) {
  47297. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47298. }
  47299. if (this.attachedElement) {
  47300. input.attachControl(this.attachedElement);
  47301. }
  47302. };
  47303. /**
  47304. * Remove a specific input method from a camera
  47305. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47306. * @param inputToRemove camera input method
  47307. */
  47308. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47309. for (var cam in this.attached) {
  47310. var input = this.attached[cam];
  47311. if (input === inputToRemove) {
  47312. input.detachControl(this.attachedElement);
  47313. input.camera = null;
  47314. delete this.attached[cam];
  47315. this.rebuildInputCheck();
  47316. }
  47317. }
  47318. };
  47319. CameraInputsManager.prototype.removeByType = function (inputType) {
  47320. for (var cam in this.attached) {
  47321. var input = this.attached[cam];
  47322. if (input.getClassName() === inputType) {
  47323. input.detachControl(this.attachedElement);
  47324. input.camera = null;
  47325. delete this.attached[cam];
  47326. this.rebuildInputCheck();
  47327. }
  47328. }
  47329. };
  47330. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47331. var current = this.checkInputs;
  47332. return function () {
  47333. current();
  47334. fn();
  47335. };
  47336. };
  47337. CameraInputsManager.prototype.attachInput = function (input) {
  47338. if (this.attachedElement) {
  47339. input.attachControl(this.attachedElement, this.noPreventDefault);
  47340. }
  47341. };
  47342. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47343. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47344. if (this.attachedElement) {
  47345. return;
  47346. }
  47347. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47348. this.attachedElement = element;
  47349. this.noPreventDefault = noPreventDefault;
  47350. for (var cam in this.attached) {
  47351. this.attached[cam].attachControl(element, noPreventDefault);
  47352. }
  47353. };
  47354. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47355. if (disconnect === void 0) { disconnect = false; }
  47356. if (this.attachedElement !== element) {
  47357. return;
  47358. }
  47359. for (var cam in this.attached) {
  47360. this.attached[cam].detachControl(element);
  47361. if (disconnect) {
  47362. this.attached[cam].camera = null;
  47363. }
  47364. }
  47365. this.attachedElement = null;
  47366. };
  47367. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47368. this.checkInputs = function () { };
  47369. for (var cam in this.attached) {
  47370. var input = this.attached[cam];
  47371. if (input.checkInputs) {
  47372. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47373. }
  47374. }
  47375. };
  47376. /**
  47377. * Remove all attached input methods from a camera
  47378. */
  47379. CameraInputsManager.prototype.clear = function () {
  47380. if (this.attachedElement) {
  47381. this.detachElement(this.attachedElement, true);
  47382. }
  47383. this.attached = {};
  47384. this.attachedElement = null;
  47385. this.checkInputs = function () { };
  47386. };
  47387. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47388. var inputs = {};
  47389. for (var cam in this.attached) {
  47390. var input = this.attached[cam];
  47391. var res = BABYLON.SerializationHelper.Serialize(input);
  47392. inputs[input.getClassName()] = res;
  47393. }
  47394. serializedCamera.inputsmgr = inputs;
  47395. };
  47396. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47397. var parsedInputs = parsedCamera.inputsmgr;
  47398. if (parsedInputs) {
  47399. this.clear();
  47400. for (var n in parsedInputs) {
  47401. var construct = BABYLON.CameraInputTypes[n];
  47402. if (construct) {
  47403. var parsedinput = parsedInputs[n];
  47404. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47405. this.add(input);
  47406. }
  47407. }
  47408. }
  47409. else {
  47410. //2016-03-08 this part is for managing backward compatibility
  47411. for (var n in this.attached) {
  47412. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47413. if (construct) {
  47414. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47415. this.remove(this.attached[n]);
  47416. this.add(input);
  47417. }
  47418. }
  47419. }
  47420. };
  47421. return CameraInputsManager;
  47422. }());
  47423. BABYLON.CameraInputsManager = CameraInputsManager;
  47424. })(BABYLON || (BABYLON = {}));
  47425. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47426. var BABYLON;
  47427. (function (BABYLON) {
  47428. var TargetCamera = /** @class */ (function (_super) {
  47429. __extends(TargetCamera, _super);
  47430. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47431. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47432. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47433. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47434. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47435. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47436. _this.speed = 2.0;
  47437. _this.noRotationConstraint = false;
  47438. _this.lockedTarget = null;
  47439. _this._currentTarget = BABYLON.Vector3.Zero();
  47440. _this._viewMatrix = BABYLON.Matrix.Zero();
  47441. _this._camMatrix = BABYLON.Matrix.Zero();
  47442. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47443. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47444. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47445. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47446. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47447. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47448. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47449. return _this;
  47450. }
  47451. TargetCamera.prototype.getFrontPosition = function (distance) {
  47452. this.getWorldMatrix();
  47453. var direction = this.getTarget().subtract(this.position);
  47454. direction.normalize();
  47455. direction.scaleInPlace(distance);
  47456. return this.globalPosition.add(direction);
  47457. };
  47458. TargetCamera.prototype._getLockedTargetPosition = function () {
  47459. if (!this.lockedTarget) {
  47460. return null;
  47461. }
  47462. if (this.lockedTarget.absolutePosition) {
  47463. this.lockedTarget.computeWorldMatrix();
  47464. }
  47465. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47466. };
  47467. TargetCamera.prototype.storeState = function () {
  47468. this._storedPosition = this.position.clone();
  47469. this._storedRotation = this.rotation.clone();
  47470. if (this.rotationQuaternion) {
  47471. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47472. }
  47473. return _super.prototype.storeState.call(this);
  47474. };
  47475. /**
  47476. * Restored camera state. You must call storeState() first
  47477. */
  47478. TargetCamera.prototype._restoreStateValues = function () {
  47479. if (!_super.prototype._restoreStateValues.call(this)) {
  47480. return false;
  47481. }
  47482. this.position = this._storedPosition.clone();
  47483. this.rotation = this._storedRotation.clone();
  47484. if (this.rotationQuaternion) {
  47485. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47486. }
  47487. this.cameraDirection.copyFromFloats(0, 0, 0);
  47488. this.cameraRotation.copyFromFloats(0, 0);
  47489. return true;
  47490. };
  47491. // Cache
  47492. TargetCamera.prototype._initCache = function () {
  47493. _super.prototype._initCache.call(this);
  47494. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47495. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47496. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47497. };
  47498. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47499. if (!ignoreParentClass) {
  47500. _super.prototype._updateCache.call(this);
  47501. }
  47502. var lockedTargetPosition = this._getLockedTargetPosition();
  47503. if (!lockedTargetPosition) {
  47504. this._cache.lockedTarget = null;
  47505. }
  47506. else {
  47507. if (!this._cache.lockedTarget) {
  47508. this._cache.lockedTarget = lockedTargetPosition.clone();
  47509. }
  47510. else {
  47511. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47512. }
  47513. }
  47514. this._cache.rotation.copyFrom(this.rotation);
  47515. if (this.rotationQuaternion)
  47516. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47517. };
  47518. // Synchronized
  47519. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47520. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47521. return false;
  47522. }
  47523. var lockedTargetPosition = this._getLockedTargetPosition();
  47524. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47525. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47526. };
  47527. // Methods
  47528. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47529. var engine = this.getEngine();
  47530. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47531. };
  47532. // Target
  47533. TargetCamera.prototype.setTarget = function (target) {
  47534. this.upVector.normalize();
  47535. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47536. this._camMatrix.invert();
  47537. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47538. var vDir = target.subtract(this.position);
  47539. if (vDir.x >= 0.0) {
  47540. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47541. }
  47542. else {
  47543. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47544. }
  47545. this.rotation.z = 0;
  47546. if (isNaN(this.rotation.x)) {
  47547. this.rotation.x = 0;
  47548. }
  47549. if (isNaN(this.rotation.y)) {
  47550. this.rotation.y = 0;
  47551. }
  47552. if (isNaN(this.rotation.z)) {
  47553. this.rotation.z = 0;
  47554. }
  47555. if (this.rotationQuaternion) {
  47556. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47557. }
  47558. };
  47559. /**
  47560. * Return the current target position of the camera. This value is expressed in local space.
  47561. */
  47562. TargetCamera.prototype.getTarget = function () {
  47563. return this._currentTarget;
  47564. };
  47565. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47566. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47567. };
  47568. TargetCamera.prototype._updatePosition = function () {
  47569. if (this.parent) {
  47570. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47571. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47572. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47573. return;
  47574. }
  47575. this.position.addInPlace(this.cameraDirection);
  47576. };
  47577. TargetCamera.prototype._checkInputs = function () {
  47578. var needToMove = this._decideIfNeedsToMove();
  47579. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47580. // Move
  47581. if (needToMove) {
  47582. this._updatePosition();
  47583. }
  47584. // Rotate
  47585. if (needToRotate) {
  47586. this.rotation.x += this.cameraRotation.x;
  47587. this.rotation.y += this.cameraRotation.y;
  47588. //rotate, if quaternion is set and rotation was used
  47589. if (this.rotationQuaternion) {
  47590. var len = this.rotation.lengthSquared();
  47591. if (len) {
  47592. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47593. }
  47594. }
  47595. if (!this.noRotationConstraint) {
  47596. var limit = (Math.PI / 2) * 0.95;
  47597. if (this.rotation.x > limit)
  47598. this.rotation.x = limit;
  47599. if (this.rotation.x < -limit)
  47600. this.rotation.x = -limit;
  47601. }
  47602. }
  47603. // Inertia
  47604. if (needToMove) {
  47605. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47606. this.cameraDirection.x = 0;
  47607. }
  47608. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47609. this.cameraDirection.y = 0;
  47610. }
  47611. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47612. this.cameraDirection.z = 0;
  47613. }
  47614. this.cameraDirection.scaleInPlace(this.inertia);
  47615. }
  47616. if (needToRotate) {
  47617. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47618. this.cameraRotation.x = 0;
  47619. }
  47620. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47621. this.cameraRotation.y = 0;
  47622. }
  47623. this.cameraRotation.scaleInPlace(this.inertia);
  47624. }
  47625. _super.prototype._checkInputs.call(this);
  47626. };
  47627. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47628. if (this.rotationQuaternion) {
  47629. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47630. }
  47631. else {
  47632. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47633. }
  47634. //update the up vector!
  47635. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47636. };
  47637. TargetCamera.prototype._getViewMatrix = function () {
  47638. if (this.lockedTarget) {
  47639. this.setTarget(this._getLockedTargetPosition());
  47640. }
  47641. // Compute
  47642. this._updateCameraRotationMatrix();
  47643. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47644. // Computing target and final matrix
  47645. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47646. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47647. return this._viewMatrix;
  47648. };
  47649. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47650. if (this.parent) {
  47651. var parentWorldMatrix = this.parent.getWorldMatrix();
  47652. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47653. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47654. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47655. this._markSyncedWithParent();
  47656. }
  47657. else {
  47658. this._globalPosition.copyFrom(this.position);
  47659. this._globalCurrentTarget.copyFrom(target);
  47660. this._globalCurrentUpVector.copyFrom(up);
  47661. }
  47662. if (this.getScene().useRightHandedSystem) {
  47663. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47664. }
  47665. else {
  47666. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47667. }
  47668. };
  47669. /**
  47670. * @override
  47671. * Override Camera.createRigCamera
  47672. */
  47673. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47674. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47675. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47676. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47677. if (!this.rotationQuaternion) {
  47678. this.rotationQuaternion = new BABYLON.Quaternion();
  47679. }
  47680. rigCamera._cameraRigParams = {};
  47681. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47682. }
  47683. return rigCamera;
  47684. }
  47685. return null;
  47686. };
  47687. /**
  47688. * @override
  47689. * Override Camera._updateRigCameras
  47690. */
  47691. TargetCamera.prototype._updateRigCameras = function () {
  47692. var camLeft = this._rigCameras[0];
  47693. var camRight = this._rigCameras[1];
  47694. switch (this.cameraRigMode) {
  47695. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47696. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47697. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47698. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47699. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47700. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47701. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47702. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47703. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47704. camLeft.setTarget(this.getTarget());
  47705. camRight.setTarget(this.getTarget());
  47706. break;
  47707. case BABYLON.Camera.RIG_MODE_VR:
  47708. if (camLeft.rotationQuaternion) {
  47709. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47710. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47711. }
  47712. else {
  47713. camLeft.rotation.copyFrom(this.rotation);
  47714. camRight.rotation.copyFrom(this.rotation);
  47715. }
  47716. camLeft.position.copyFrom(this.position);
  47717. camRight.position.copyFrom(this.position);
  47718. break;
  47719. }
  47720. _super.prototype._updateRigCameras.call(this);
  47721. };
  47722. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47723. if (!this._rigCamTransformMatrix) {
  47724. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47725. }
  47726. var target = this.getTarget();
  47727. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47728. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47729. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47730. };
  47731. TargetCamera.prototype.getClassName = function () {
  47732. return "TargetCamera";
  47733. };
  47734. __decorate([
  47735. BABYLON.serializeAsVector3()
  47736. ], TargetCamera.prototype, "rotation", void 0);
  47737. __decorate([
  47738. BABYLON.serialize()
  47739. ], TargetCamera.prototype, "speed", void 0);
  47740. __decorate([
  47741. BABYLON.serializeAsMeshReference("lockedTargetId")
  47742. ], TargetCamera.prototype, "lockedTarget", void 0);
  47743. return TargetCamera;
  47744. }(BABYLON.Camera));
  47745. BABYLON.TargetCamera = TargetCamera;
  47746. })(BABYLON || (BABYLON = {}));
  47747. //# sourceMappingURL=babylon.targetCamera.js.map
  47748. var BABYLON;
  47749. (function (BABYLON) {
  47750. var FreeCameraMouseInput = /** @class */ (function () {
  47751. function FreeCameraMouseInput(touchEnabled) {
  47752. if (touchEnabled === void 0) { touchEnabled = true; }
  47753. this.touchEnabled = touchEnabled;
  47754. this.buttons = [0, 1, 2];
  47755. this.angularSensibility = 2000.0;
  47756. this.previousPosition = null;
  47757. }
  47758. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47759. var _this = this;
  47760. var engine = this.camera.getEngine();
  47761. if (!this._pointerInput) {
  47762. this._pointerInput = function (p, s) {
  47763. var evt = p.event;
  47764. if (engine.isInVRExclusivePointerMode) {
  47765. return;
  47766. }
  47767. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47768. return;
  47769. }
  47770. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47771. return;
  47772. }
  47773. var srcElement = (evt.srcElement || evt.target);
  47774. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47775. try {
  47776. srcElement.setPointerCapture(evt.pointerId);
  47777. }
  47778. catch (e) {
  47779. //Nothing to do with the error. Execution will continue.
  47780. }
  47781. _this.previousPosition = {
  47782. x: evt.clientX,
  47783. y: evt.clientY
  47784. };
  47785. if (!noPreventDefault) {
  47786. evt.preventDefault();
  47787. element.focus();
  47788. }
  47789. }
  47790. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47791. try {
  47792. srcElement.releasePointerCapture(evt.pointerId);
  47793. }
  47794. catch (e) {
  47795. //Nothing to do with the error.
  47796. }
  47797. _this.previousPosition = null;
  47798. if (!noPreventDefault) {
  47799. evt.preventDefault();
  47800. }
  47801. }
  47802. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47803. if (!_this.previousPosition || engine.isPointerLock) {
  47804. return;
  47805. }
  47806. var offsetX = evt.clientX - _this.previousPosition.x;
  47807. if (_this.camera.getScene().useRightHandedSystem)
  47808. offsetX *= -1;
  47809. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47810. offsetX *= -1;
  47811. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47812. var offsetY = evt.clientY - _this.previousPosition.y;
  47813. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47814. _this.previousPosition = {
  47815. x: evt.clientX,
  47816. y: evt.clientY
  47817. };
  47818. if (!noPreventDefault) {
  47819. evt.preventDefault();
  47820. }
  47821. }
  47822. };
  47823. }
  47824. this._onMouseMove = function (evt) {
  47825. if (!engine.isPointerLock) {
  47826. return;
  47827. }
  47828. if (engine.isInVRExclusivePointerMode) {
  47829. return;
  47830. }
  47831. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47832. if (_this.camera.getScene().useRightHandedSystem)
  47833. offsetX *= -1;
  47834. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47835. offsetX *= -1;
  47836. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47837. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47838. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47839. _this.previousPosition = null;
  47840. if (!noPreventDefault) {
  47841. evt.preventDefault();
  47842. }
  47843. };
  47844. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47845. element.addEventListener("mousemove", this._onMouseMove, false);
  47846. };
  47847. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47848. if (this._observer && element) {
  47849. this.camera.getScene().onPointerObservable.remove(this._observer);
  47850. if (this._onMouseMove) {
  47851. element.removeEventListener("mousemove", this._onMouseMove);
  47852. }
  47853. this._observer = null;
  47854. this._onMouseMove = null;
  47855. this.previousPosition = null;
  47856. }
  47857. };
  47858. FreeCameraMouseInput.prototype.getClassName = function () {
  47859. return "FreeCameraMouseInput";
  47860. };
  47861. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47862. return "mouse";
  47863. };
  47864. __decorate([
  47865. BABYLON.serialize()
  47866. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47867. __decorate([
  47868. BABYLON.serialize()
  47869. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47870. return FreeCameraMouseInput;
  47871. }());
  47872. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47873. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47874. })(BABYLON || (BABYLON = {}));
  47875. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47876. var BABYLON;
  47877. (function (BABYLON) {
  47878. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47879. function FreeCameraKeyboardMoveInput() {
  47880. this._keys = new Array();
  47881. this.keysUp = [38];
  47882. this.keysDown = [40];
  47883. this.keysLeft = [37];
  47884. this.keysRight = [39];
  47885. }
  47886. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47887. var _this = this;
  47888. if (this._onCanvasBlurObserver) {
  47889. return;
  47890. }
  47891. this._scene = this.camera.getScene();
  47892. this._engine = this._scene.getEngine();
  47893. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47894. _this._keys = [];
  47895. });
  47896. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47897. var evt = info.event;
  47898. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47899. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47900. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47901. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47902. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47903. var index = _this._keys.indexOf(evt.keyCode);
  47904. if (index === -1) {
  47905. _this._keys.push(evt.keyCode);
  47906. }
  47907. if (!noPreventDefault) {
  47908. evt.preventDefault();
  47909. }
  47910. }
  47911. }
  47912. else {
  47913. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47914. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47915. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47916. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47917. var index = _this._keys.indexOf(evt.keyCode);
  47918. if (index >= 0) {
  47919. _this._keys.splice(index, 1);
  47920. }
  47921. if (!noPreventDefault) {
  47922. evt.preventDefault();
  47923. }
  47924. }
  47925. }
  47926. });
  47927. };
  47928. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47929. if (this._scene) {
  47930. if (this._onKeyboardObserver) {
  47931. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47932. }
  47933. if (this._onCanvasBlurObserver) {
  47934. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47935. }
  47936. this._onKeyboardObserver = null;
  47937. this._onCanvasBlurObserver = null;
  47938. }
  47939. this._keys = [];
  47940. };
  47941. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47942. if (this._onKeyboardObserver) {
  47943. var camera = this.camera;
  47944. // Keyboard
  47945. for (var index = 0; index < this._keys.length; index++) {
  47946. var keyCode = this._keys[index];
  47947. var speed = camera._computeLocalCameraSpeed();
  47948. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47949. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47950. }
  47951. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47952. camera._localDirection.copyFromFloats(0, 0, speed);
  47953. }
  47954. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47955. camera._localDirection.copyFromFloats(speed, 0, 0);
  47956. }
  47957. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47958. camera._localDirection.copyFromFloats(0, 0, -speed);
  47959. }
  47960. if (camera.getScene().useRightHandedSystem) {
  47961. camera._localDirection.z *= -1;
  47962. }
  47963. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47964. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47965. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47966. }
  47967. }
  47968. };
  47969. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47970. return "FreeCameraKeyboardMoveInput";
  47971. };
  47972. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47973. this._keys = [];
  47974. };
  47975. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47976. return "keyboard";
  47977. };
  47978. __decorate([
  47979. BABYLON.serialize()
  47980. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47981. __decorate([
  47982. BABYLON.serialize()
  47983. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47984. __decorate([
  47985. BABYLON.serialize()
  47986. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47987. __decorate([
  47988. BABYLON.serialize()
  47989. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47990. return FreeCameraKeyboardMoveInput;
  47991. }());
  47992. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47993. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47994. })(BABYLON || (BABYLON = {}));
  47995. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47996. var BABYLON;
  47997. (function (BABYLON) {
  47998. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47999. __extends(FreeCameraInputsManager, _super);
  48000. function FreeCameraInputsManager(camera) {
  48001. return _super.call(this, camera) || this;
  48002. }
  48003. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48004. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48005. return this;
  48006. };
  48007. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48008. if (touchEnabled === void 0) { touchEnabled = true; }
  48009. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48010. return this;
  48011. };
  48012. FreeCameraInputsManager.prototype.addGamepad = function () {
  48013. this.add(new BABYLON.FreeCameraGamepadInput());
  48014. return this;
  48015. };
  48016. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48017. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48018. return this;
  48019. };
  48020. FreeCameraInputsManager.prototype.addTouch = function () {
  48021. this.add(new BABYLON.FreeCameraTouchInput());
  48022. return this;
  48023. };
  48024. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48025. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48026. return this;
  48027. };
  48028. return FreeCameraInputsManager;
  48029. }(BABYLON.CameraInputsManager));
  48030. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48031. })(BABYLON || (BABYLON = {}));
  48032. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48033. var BABYLON;
  48034. (function (BABYLON) {
  48035. var FreeCamera = /** @class */ (function (_super) {
  48036. __extends(FreeCamera, _super);
  48037. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48038. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48039. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48040. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48041. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48042. _this.checkCollisions = false;
  48043. _this.applyGravity = false;
  48044. _this._needMoveForGravity = false;
  48045. _this._oldPosition = BABYLON.Vector3.Zero();
  48046. _this._diffPosition = BABYLON.Vector3.Zero();
  48047. _this._newPosition = BABYLON.Vector3.Zero();
  48048. // Collisions
  48049. _this._collisionMask = -1;
  48050. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48051. if (collidedMesh === void 0) { collidedMesh = null; }
  48052. //TODO move this to the collision coordinator!
  48053. if (_this.getScene().workerCollisions)
  48054. newPosition.multiplyInPlace(_this._collider._radius);
  48055. var updatePosition = function (newPos) {
  48056. _this._newPosition.copyFrom(newPos);
  48057. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48058. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48059. _this.position.addInPlace(_this._diffPosition);
  48060. if (_this.onCollide && collidedMesh) {
  48061. _this.onCollide(collidedMesh);
  48062. }
  48063. }
  48064. };
  48065. updatePosition(newPosition);
  48066. };
  48067. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48068. _this.inputs.addKeyboard().addMouse();
  48069. return _this;
  48070. }
  48071. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48072. //-- begin properties for backward compatibility for inputs
  48073. /**
  48074. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48075. * Higher values reduce sensitivity.
  48076. */
  48077. get: function () {
  48078. var mouse = this.inputs.attached["mouse"];
  48079. if (mouse)
  48080. return mouse.angularSensibility;
  48081. return 0;
  48082. },
  48083. /**
  48084. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48085. * Higher values reduce sensitivity.
  48086. */
  48087. set: function (value) {
  48088. var mouse = this.inputs.attached["mouse"];
  48089. if (mouse)
  48090. mouse.angularSensibility = value;
  48091. },
  48092. enumerable: true,
  48093. configurable: true
  48094. });
  48095. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48096. get: function () {
  48097. var keyboard = this.inputs.attached["keyboard"];
  48098. if (keyboard)
  48099. return keyboard.keysUp;
  48100. return [];
  48101. },
  48102. set: function (value) {
  48103. var keyboard = this.inputs.attached["keyboard"];
  48104. if (keyboard)
  48105. keyboard.keysUp = value;
  48106. },
  48107. enumerable: true,
  48108. configurable: true
  48109. });
  48110. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48111. get: function () {
  48112. var keyboard = this.inputs.attached["keyboard"];
  48113. if (keyboard)
  48114. return keyboard.keysDown;
  48115. return [];
  48116. },
  48117. set: function (value) {
  48118. var keyboard = this.inputs.attached["keyboard"];
  48119. if (keyboard)
  48120. keyboard.keysDown = value;
  48121. },
  48122. enumerable: true,
  48123. configurable: true
  48124. });
  48125. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48126. get: function () {
  48127. var keyboard = this.inputs.attached["keyboard"];
  48128. if (keyboard)
  48129. return keyboard.keysLeft;
  48130. return [];
  48131. },
  48132. set: function (value) {
  48133. var keyboard = this.inputs.attached["keyboard"];
  48134. if (keyboard)
  48135. keyboard.keysLeft = value;
  48136. },
  48137. enumerable: true,
  48138. configurable: true
  48139. });
  48140. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48141. get: function () {
  48142. var keyboard = this.inputs.attached["keyboard"];
  48143. if (keyboard)
  48144. return keyboard.keysRight;
  48145. return [];
  48146. },
  48147. set: function (value) {
  48148. var keyboard = this.inputs.attached["keyboard"];
  48149. if (keyboard)
  48150. keyboard.keysRight = value;
  48151. },
  48152. enumerable: true,
  48153. configurable: true
  48154. });
  48155. // Controls
  48156. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48157. this.inputs.attachElement(element, noPreventDefault);
  48158. };
  48159. FreeCamera.prototype.detachControl = function (element) {
  48160. this.inputs.detachElement(element);
  48161. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48162. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48163. };
  48164. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48165. get: function () {
  48166. return this._collisionMask;
  48167. },
  48168. set: function (mask) {
  48169. this._collisionMask = !isNaN(mask) ? mask : -1;
  48170. },
  48171. enumerable: true,
  48172. configurable: true
  48173. });
  48174. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48175. var globalPosition;
  48176. if (this.parent) {
  48177. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48178. }
  48179. else {
  48180. globalPosition = this.position;
  48181. }
  48182. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48183. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48184. if (!this._collider) {
  48185. this._collider = new BABYLON.Collider();
  48186. }
  48187. this._collider._radius = this.ellipsoid;
  48188. this._collider.collisionMask = this._collisionMask;
  48189. //no need for clone, as long as gravity is not on.
  48190. var actualDisplacement = displacement;
  48191. //add gravity to the direction to prevent the dual-collision checking
  48192. if (this.applyGravity) {
  48193. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48194. actualDisplacement = displacement.add(this.getScene().gravity);
  48195. }
  48196. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48197. };
  48198. FreeCamera.prototype._checkInputs = function () {
  48199. if (!this._localDirection) {
  48200. this._localDirection = BABYLON.Vector3.Zero();
  48201. this._transformedDirection = BABYLON.Vector3.Zero();
  48202. }
  48203. this.inputs.checkInputs();
  48204. _super.prototype._checkInputs.call(this);
  48205. };
  48206. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48207. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48208. };
  48209. FreeCamera.prototype._updatePosition = function () {
  48210. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48211. this._collideWithWorld(this.cameraDirection);
  48212. }
  48213. else {
  48214. _super.prototype._updatePosition.call(this);
  48215. }
  48216. };
  48217. FreeCamera.prototype.dispose = function () {
  48218. this.inputs.clear();
  48219. _super.prototype.dispose.call(this);
  48220. };
  48221. FreeCamera.prototype.getClassName = function () {
  48222. return "FreeCamera";
  48223. };
  48224. __decorate([
  48225. BABYLON.serializeAsVector3()
  48226. ], FreeCamera.prototype, "ellipsoid", void 0);
  48227. __decorate([
  48228. BABYLON.serializeAsVector3()
  48229. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48230. __decorate([
  48231. BABYLON.serialize()
  48232. ], FreeCamera.prototype, "checkCollisions", void 0);
  48233. __decorate([
  48234. BABYLON.serialize()
  48235. ], FreeCamera.prototype, "applyGravity", void 0);
  48236. return FreeCamera;
  48237. }(BABYLON.TargetCamera));
  48238. BABYLON.FreeCamera = FreeCamera;
  48239. })(BABYLON || (BABYLON = {}));
  48240. //# sourceMappingURL=babylon.freeCamera.js.map
  48241. var BABYLON;
  48242. (function (BABYLON) {
  48243. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48244. function ArcRotateCameraKeyboardMoveInput() {
  48245. this._keys = new Array();
  48246. this.keysUp = [38];
  48247. this.keysDown = [40];
  48248. this.keysLeft = [37];
  48249. this.keysRight = [39];
  48250. this.keysReset = [220];
  48251. this.panningSensibility = 50.0;
  48252. this.zoomingSensibility = 25.0;
  48253. this.useAltToZoom = true;
  48254. }
  48255. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48256. var _this = this;
  48257. if (this._onCanvasBlurObserver) {
  48258. return;
  48259. }
  48260. this._scene = this.camera.getScene();
  48261. this._engine = this._scene.getEngine();
  48262. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48263. _this._keys = [];
  48264. });
  48265. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48266. var evt = info.event;
  48267. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48268. _this._ctrlPressed = evt.ctrlKey;
  48269. _this._altPressed = evt.altKey;
  48270. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48271. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48272. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48273. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48274. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48275. var index = _this._keys.indexOf(evt.keyCode);
  48276. if (index === -1) {
  48277. _this._keys.push(evt.keyCode);
  48278. }
  48279. if (evt.preventDefault) {
  48280. if (!noPreventDefault) {
  48281. evt.preventDefault();
  48282. }
  48283. }
  48284. }
  48285. }
  48286. else {
  48287. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48288. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48289. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48290. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48291. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48292. var index = _this._keys.indexOf(evt.keyCode);
  48293. if (index >= 0) {
  48294. _this._keys.splice(index, 1);
  48295. }
  48296. if (evt.preventDefault) {
  48297. if (!noPreventDefault) {
  48298. evt.preventDefault();
  48299. }
  48300. }
  48301. }
  48302. }
  48303. });
  48304. };
  48305. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48306. if (this._scene) {
  48307. if (this._onKeyboardObserver) {
  48308. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48309. }
  48310. if (this._onCanvasBlurObserver) {
  48311. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48312. }
  48313. this._onKeyboardObserver = null;
  48314. this._onCanvasBlurObserver = null;
  48315. }
  48316. this._keys = [];
  48317. };
  48318. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48319. if (this._onKeyboardObserver) {
  48320. var camera = this.camera;
  48321. for (var index = 0; index < this._keys.length; index++) {
  48322. var keyCode = this._keys[index];
  48323. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48324. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48325. camera.inertialPanningX -= 1 / this.panningSensibility;
  48326. }
  48327. else {
  48328. camera.inertialAlphaOffset -= 0.01;
  48329. }
  48330. }
  48331. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48332. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48333. camera.inertialPanningY += 1 / this.panningSensibility;
  48334. }
  48335. else if (this._altPressed && this.useAltToZoom) {
  48336. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48337. }
  48338. else {
  48339. camera.inertialBetaOffset -= 0.01;
  48340. }
  48341. }
  48342. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48343. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48344. camera.inertialPanningX += 1 / this.panningSensibility;
  48345. }
  48346. else {
  48347. camera.inertialAlphaOffset += 0.01;
  48348. }
  48349. }
  48350. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48351. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48352. camera.inertialPanningY -= 1 / this.panningSensibility;
  48353. }
  48354. else if (this._altPressed && this.useAltToZoom) {
  48355. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48356. }
  48357. else {
  48358. camera.inertialBetaOffset += 0.01;
  48359. }
  48360. }
  48361. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48362. camera.restoreState();
  48363. }
  48364. }
  48365. }
  48366. };
  48367. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48368. return "ArcRotateCameraKeyboardMoveInput";
  48369. };
  48370. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48371. return "keyboard";
  48372. };
  48373. __decorate([
  48374. BABYLON.serialize()
  48375. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48376. __decorate([
  48377. BABYLON.serialize()
  48378. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48379. __decorate([
  48380. BABYLON.serialize()
  48381. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48382. __decorate([
  48383. BABYLON.serialize()
  48384. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48385. __decorate([
  48386. BABYLON.serialize()
  48387. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48388. __decorate([
  48389. BABYLON.serialize()
  48390. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48391. __decorate([
  48392. BABYLON.serialize()
  48393. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48394. __decorate([
  48395. BABYLON.serialize()
  48396. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48397. return ArcRotateCameraKeyboardMoveInput;
  48398. }());
  48399. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48400. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48401. })(BABYLON || (BABYLON = {}));
  48402. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48403. var BABYLON;
  48404. (function (BABYLON) {
  48405. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48406. function ArcRotateCameraMouseWheelInput() {
  48407. this.wheelPrecision = 3.0;
  48408. /**
  48409. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48410. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48411. */
  48412. this.wheelDeltaPercentage = 0;
  48413. }
  48414. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48415. var _this = this;
  48416. this._wheel = function (p, s) {
  48417. //sanity check - this should be a PointerWheel event.
  48418. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48419. return;
  48420. var event = p.event;
  48421. var delta = 0;
  48422. if (event.wheelDelta) {
  48423. if (_this.wheelDeltaPercentage) {
  48424. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48425. if (event.wheelDelta > 0) {
  48426. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48427. }
  48428. else {
  48429. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48430. }
  48431. }
  48432. else {
  48433. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48434. }
  48435. }
  48436. else if (event.detail) {
  48437. delta = -event.detail / _this.wheelPrecision;
  48438. }
  48439. if (delta)
  48440. _this.camera.inertialRadiusOffset += delta;
  48441. if (event.preventDefault) {
  48442. if (!noPreventDefault) {
  48443. event.preventDefault();
  48444. }
  48445. }
  48446. };
  48447. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48448. };
  48449. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48450. if (this._observer && element) {
  48451. this.camera.getScene().onPointerObservable.remove(this._observer);
  48452. this._observer = null;
  48453. this._wheel = null;
  48454. }
  48455. };
  48456. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48457. return "ArcRotateCameraMouseWheelInput";
  48458. };
  48459. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48460. return "mousewheel";
  48461. };
  48462. __decorate([
  48463. BABYLON.serialize()
  48464. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48465. __decorate([
  48466. BABYLON.serialize()
  48467. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48468. return ArcRotateCameraMouseWheelInput;
  48469. }());
  48470. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48471. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48472. })(BABYLON || (BABYLON = {}));
  48473. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48474. var BABYLON;
  48475. (function (BABYLON) {
  48476. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48477. function ArcRotateCameraPointersInput() {
  48478. this.buttons = [0, 1, 2];
  48479. this.angularSensibilityX = 1000.0;
  48480. this.angularSensibilityY = 1000.0;
  48481. this.pinchPrecision = 12.0;
  48482. /**
  48483. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48484. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48485. */
  48486. this.pinchDeltaPercentage = 0;
  48487. this.panningSensibility = 1000.0;
  48488. this.multiTouchPanning = true;
  48489. this.multiTouchPanAndZoom = true;
  48490. this._isPanClick = false;
  48491. this.pinchInwards = true;
  48492. }
  48493. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48494. var _this = this;
  48495. var engine = this.camera.getEngine();
  48496. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48497. var pointA = null;
  48498. var pointB = null;
  48499. var previousPinchSquaredDistance = 0;
  48500. var initialDistance = 0;
  48501. var twoFingerActivityCount = 0;
  48502. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48503. this._pointerInput = function (p, s) {
  48504. var evt = p.event;
  48505. var isTouch = p.event.pointerType === "touch";
  48506. if (engine.isInVRExclusivePointerMode) {
  48507. return;
  48508. }
  48509. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48510. return;
  48511. }
  48512. var srcElement = (evt.srcElement || evt.target);
  48513. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48514. try {
  48515. srcElement.setPointerCapture(evt.pointerId);
  48516. }
  48517. catch (e) {
  48518. //Nothing to do with the error. Execution will continue.
  48519. }
  48520. // Manage panning with pan button click
  48521. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48522. // manage pointers
  48523. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48524. if (pointA === null) {
  48525. pointA = cacheSoloPointer;
  48526. }
  48527. else if (pointB === null) {
  48528. pointB = cacheSoloPointer;
  48529. }
  48530. if (!noPreventDefault) {
  48531. evt.preventDefault();
  48532. element.focus();
  48533. }
  48534. }
  48535. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48536. _this.camera.restoreState();
  48537. }
  48538. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48539. try {
  48540. srcElement.releasePointerCapture(evt.pointerId);
  48541. }
  48542. catch (e) {
  48543. //Nothing to do with the error.
  48544. }
  48545. cacheSoloPointer = null;
  48546. previousPinchSquaredDistance = 0;
  48547. previousMultiTouchPanPosition.isPaning = false;
  48548. previousMultiTouchPanPosition.isPinching = false;
  48549. twoFingerActivityCount = 0;
  48550. initialDistance = 0;
  48551. if (!isTouch) {
  48552. pointB = null; // Mouse and pen are mono pointer
  48553. }
  48554. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48555. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48556. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48557. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48558. if (engine._badOS) {
  48559. pointA = pointB = null;
  48560. }
  48561. else {
  48562. //only remove the impacted pointer in case of multitouch allowing on most
  48563. //platforms switching from rotate to zoom and pan seamlessly.
  48564. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48565. pointA = pointB;
  48566. pointB = null;
  48567. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48568. }
  48569. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48570. pointB = null;
  48571. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48572. }
  48573. else {
  48574. pointA = pointB = null;
  48575. }
  48576. }
  48577. if (!noPreventDefault) {
  48578. evt.preventDefault();
  48579. }
  48580. }
  48581. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48582. if (!noPreventDefault) {
  48583. evt.preventDefault();
  48584. }
  48585. // One button down
  48586. if (pointA && pointB === null && cacheSoloPointer) {
  48587. if (_this.panningSensibility !== 0 &&
  48588. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48589. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48590. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48591. }
  48592. else {
  48593. var offsetX = evt.clientX - cacheSoloPointer.x;
  48594. var offsetY = evt.clientY - cacheSoloPointer.y;
  48595. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48596. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48597. }
  48598. cacheSoloPointer.x = evt.clientX;
  48599. cacheSoloPointer.y = evt.clientY;
  48600. }
  48601. // Two buttons down: pinch/pan
  48602. else if (pointA && pointB) {
  48603. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48604. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48605. ed.x = evt.clientX;
  48606. ed.y = evt.clientY;
  48607. var direction = _this.pinchInwards ? 1 : -1;
  48608. var distX = pointA.x - pointB.x;
  48609. var distY = pointA.y - pointB.y;
  48610. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48611. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48612. if (previousPinchSquaredDistance === 0) {
  48613. initialDistance = pinchDistance;
  48614. previousPinchSquaredDistance = pinchSquaredDistance;
  48615. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48616. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48617. return;
  48618. }
  48619. if (_this.multiTouchPanAndZoom) {
  48620. if (_this.pinchDeltaPercentage) {
  48621. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48622. }
  48623. else {
  48624. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48625. (_this.pinchPrecision *
  48626. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48627. direction);
  48628. }
  48629. if (_this.panningSensibility !== 0) {
  48630. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48631. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48632. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48633. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48634. previousMultiTouchPanPosition.x = pointersCenterX;
  48635. previousMultiTouchPanPosition.y = pointersCenterY;
  48636. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48637. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48638. }
  48639. }
  48640. else {
  48641. twoFingerActivityCount++;
  48642. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48643. if (_this.pinchDeltaPercentage) {
  48644. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48645. }
  48646. else {
  48647. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48648. (_this.pinchPrecision *
  48649. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48650. direction);
  48651. }
  48652. previousMultiTouchPanPosition.isPaning = false;
  48653. previousMultiTouchPanPosition.isPinching = true;
  48654. }
  48655. else {
  48656. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48657. if (!previousMultiTouchPanPosition.isPaning) {
  48658. previousMultiTouchPanPosition.isPaning = true;
  48659. previousMultiTouchPanPosition.isPinching = false;
  48660. previousMultiTouchPanPosition.x = ed.x;
  48661. previousMultiTouchPanPosition.y = ed.y;
  48662. return;
  48663. }
  48664. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48665. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48666. }
  48667. }
  48668. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48669. previousMultiTouchPanPosition.x = ed.x;
  48670. previousMultiTouchPanPosition.y = ed.y;
  48671. }
  48672. }
  48673. previousPinchSquaredDistance = pinchSquaredDistance;
  48674. }
  48675. }
  48676. };
  48677. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48678. this._onContextMenu = function (evt) {
  48679. evt.preventDefault();
  48680. };
  48681. if (!this.camera._useCtrlForPanning) {
  48682. element.addEventListener("contextmenu", this._onContextMenu, false);
  48683. }
  48684. this._onLostFocus = function () {
  48685. //this._keys = [];
  48686. pointA = pointB = null;
  48687. previousPinchSquaredDistance = 0;
  48688. previousMultiTouchPanPosition.isPaning = false;
  48689. previousMultiTouchPanPosition.isPinching = false;
  48690. twoFingerActivityCount = 0;
  48691. cacheSoloPointer = null;
  48692. initialDistance = 0;
  48693. };
  48694. this._onMouseMove = function (evt) {
  48695. if (!engine.isPointerLock) {
  48696. return;
  48697. }
  48698. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48699. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48700. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48701. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48702. if (!noPreventDefault) {
  48703. evt.preventDefault();
  48704. }
  48705. };
  48706. this._onGestureStart = function (e) {
  48707. if (window.MSGesture === undefined) {
  48708. return;
  48709. }
  48710. if (!_this._MSGestureHandler) {
  48711. _this._MSGestureHandler = new MSGesture();
  48712. _this._MSGestureHandler.target = element;
  48713. }
  48714. _this._MSGestureHandler.addPointer(e.pointerId);
  48715. };
  48716. this._onGesture = function (e) {
  48717. _this.camera.radius *= e.scale;
  48718. if (e.preventDefault) {
  48719. if (!noPreventDefault) {
  48720. e.stopPropagation();
  48721. e.preventDefault();
  48722. }
  48723. }
  48724. };
  48725. element.addEventListener("mousemove", this._onMouseMove, false);
  48726. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48727. element.addEventListener("MSGestureChange", this._onGesture, false);
  48728. BABYLON.Tools.RegisterTopRootEvents([
  48729. { name: "blur", handler: this._onLostFocus }
  48730. ]);
  48731. };
  48732. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48733. if (this._onLostFocus) {
  48734. BABYLON.Tools.UnregisterTopRootEvents([
  48735. { name: "blur", handler: this._onLostFocus }
  48736. ]);
  48737. }
  48738. if (element && this._observer) {
  48739. this.camera.getScene().onPointerObservable.remove(this._observer);
  48740. this._observer = null;
  48741. if (this._onContextMenu) {
  48742. element.removeEventListener("contextmenu", this._onContextMenu);
  48743. }
  48744. if (this._onMouseMove) {
  48745. element.removeEventListener("mousemove", this._onMouseMove);
  48746. }
  48747. if (this._onGestureStart) {
  48748. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48749. }
  48750. if (this._onGesture) {
  48751. element.removeEventListener("MSGestureChange", this._onGesture);
  48752. }
  48753. this._isPanClick = false;
  48754. this.pinchInwards = true;
  48755. this._onMouseMove = null;
  48756. this._onGestureStart = null;
  48757. this._onGesture = null;
  48758. this._MSGestureHandler = null;
  48759. this._onLostFocus = null;
  48760. this._onContextMenu = null;
  48761. }
  48762. };
  48763. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48764. return "ArcRotateCameraPointersInput";
  48765. };
  48766. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48767. return "pointers";
  48768. };
  48769. __decorate([
  48770. BABYLON.serialize()
  48771. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48772. __decorate([
  48773. BABYLON.serialize()
  48774. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48775. __decorate([
  48776. BABYLON.serialize()
  48777. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48778. __decorate([
  48779. BABYLON.serialize()
  48780. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48781. __decorate([
  48782. BABYLON.serialize()
  48783. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48784. __decorate([
  48785. BABYLON.serialize()
  48786. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48787. __decorate([
  48788. BABYLON.serialize()
  48789. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48790. __decorate([
  48791. BABYLON.serialize()
  48792. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48793. return ArcRotateCameraPointersInput;
  48794. }());
  48795. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48796. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48797. })(BABYLON || (BABYLON = {}));
  48798. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48799. var BABYLON;
  48800. (function (BABYLON) {
  48801. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48802. __extends(ArcRotateCameraInputsManager, _super);
  48803. function ArcRotateCameraInputsManager(camera) {
  48804. return _super.call(this, camera) || this;
  48805. }
  48806. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48807. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48808. return this;
  48809. };
  48810. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48811. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48812. return this;
  48813. };
  48814. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48815. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48816. return this;
  48817. };
  48818. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48819. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48820. return this;
  48821. };
  48822. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48823. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48824. return this;
  48825. };
  48826. return ArcRotateCameraInputsManager;
  48827. }(BABYLON.CameraInputsManager));
  48828. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48829. })(BABYLON || (BABYLON = {}));
  48830. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48831. var BABYLON;
  48832. (function (BABYLON) {
  48833. var ArcRotateCamera = /** @class */ (function (_super) {
  48834. __extends(ArcRotateCamera, _super);
  48835. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48836. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48837. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48838. _this.inertialAlphaOffset = 0;
  48839. _this.inertialBetaOffset = 0;
  48840. _this.inertialRadiusOffset = 0;
  48841. _this.lowerAlphaLimit = null;
  48842. _this.upperAlphaLimit = null;
  48843. _this.lowerBetaLimit = 0.01;
  48844. _this.upperBetaLimit = Math.PI;
  48845. _this.lowerRadiusLimit = null;
  48846. _this.upperRadiusLimit = null;
  48847. _this.inertialPanningX = 0;
  48848. _this.inertialPanningY = 0;
  48849. _this.pinchToPanMaxDistance = 20;
  48850. _this.panningDistanceLimit = null;
  48851. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48852. _this.panningInertia = 0.9;
  48853. //-- end properties for backward compatibility for inputs
  48854. _this.zoomOnFactor = 1;
  48855. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48856. _this.allowUpsideDown = true;
  48857. _this._viewMatrix = new BABYLON.Matrix();
  48858. // Panning
  48859. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48860. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48861. _this.checkCollisions = false;
  48862. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48863. _this._previousPosition = BABYLON.Vector3.Zero();
  48864. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48865. _this._newPosition = BABYLON.Vector3.Zero();
  48866. _this._computationVector = BABYLON.Vector3.Zero();
  48867. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48868. if (collidedMesh === void 0) { collidedMesh = null; }
  48869. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48870. newPosition.multiplyInPlace(_this._collider._radius);
  48871. }
  48872. if (!collidedMesh) {
  48873. _this._previousPosition.copyFrom(_this.position);
  48874. }
  48875. else {
  48876. _this.setPosition(newPosition);
  48877. if (_this.onCollide) {
  48878. _this.onCollide(collidedMesh);
  48879. }
  48880. }
  48881. // Recompute because of constraints
  48882. var cosa = Math.cos(_this.alpha);
  48883. var sina = Math.sin(_this.alpha);
  48884. var cosb = Math.cos(_this.beta);
  48885. var sinb = Math.sin(_this.beta);
  48886. if (sinb === 0) {
  48887. sinb = 0.0001;
  48888. }
  48889. var target = _this._getTargetPosition();
  48890. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48891. target.addToRef(_this._computationVector, _this._newPosition);
  48892. _this.position.copyFrom(_this._newPosition);
  48893. var up = _this.upVector;
  48894. if (_this.allowUpsideDown && _this.beta < 0) {
  48895. up = up.clone();
  48896. up = up.negate();
  48897. }
  48898. _this._computeViewMatrix(_this.position, target, up);
  48899. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48900. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48901. _this._collisionTriggered = false;
  48902. };
  48903. _this._target = BABYLON.Vector3.Zero();
  48904. if (target) {
  48905. _this.setTarget(target);
  48906. }
  48907. _this.alpha = alpha;
  48908. _this.beta = beta;
  48909. _this.radius = radius;
  48910. _this.getViewMatrix();
  48911. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48912. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48913. return _this;
  48914. }
  48915. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48916. get: function () {
  48917. return this._target;
  48918. },
  48919. set: function (value) {
  48920. this.setTarget(value);
  48921. },
  48922. enumerable: true,
  48923. configurable: true
  48924. });
  48925. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48926. //-- begin properties for backward compatibility for inputs
  48927. get: function () {
  48928. var pointers = this.inputs.attached["pointers"];
  48929. if (pointers)
  48930. return pointers.angularSensibilityX;
  48931. return 0;
  48932. },
  48933. set: function (value) {
  48934. var pointers = this.inputs.attached["pointers"];
  48935. if (pointers) {
  48936. pointers.angularSensibilityX = value;
  48937. }
  48938. },
  48939. enumerable: true,
  48940. configurable: true
  48941. });
  48942. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48943. get: function () {
  48944. var pointers = this.inputs.attached["pointers"];
  48945. if (pointers)
  48946. return pointers.angularSensibilityY;
  48947. return 0;
  48948. },
  48949. set: function (value) {
  48950. var pointers = this.inputs.attached["pointers"];
  48951. if (pointers) {
  48952. pointers.angularSensibilityY = value;
  48953. }
  48954. },
  48955. enumerable: true,
  48956. configurable: true
  48957. });
  48958. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48959. get: function () {
  48960. var pointers = this.inputs.attached["pointers"];
  48961. if (pointers)
  48962. return pointers.pinchPrecision;
  48963. return 0;
  48964. },
  48965. set: function (value) {
  48966. var pointers = this.inputs.attached["pointers"];
  48967. if (pointers) {
  48968. pointers.pinchPrecision = value;
  48969. }
  48970. },
  48971. enumerable: true,
  48972. configurable: true
  48973. });
  48974. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48975. get: function () {
  48976. var pointers = this.inputs.attached["pointers"];
  48977. if (pointers)
  48978. return pointers.pinchDeltaPercentage;
  48979. return 0;
  48980. },
  48981. set: function (value) {
  48982. var pointers = this.inputs.attached["pointers"];
  48983. if (pointers) {
  48984. pointers.pinchDeltaPercentage = value;
  48985. }
  48986. },
  48987. enumerable: true,
  48988. configurable: true
  48989. });
  48990. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48991. get: function () {
  48992. var pointers = this.inputs.attached["pointers"];
  48993. if (pointers)
  48994. return pointers.panningSensibility;
  48995. return 0;
  48996. },
  48997. set: function (value) {
  48998. var pointers = this.inputs.attached["pointers"];
  48999. if (pointers) {
  49000. pointers.panningSensibility = value;
  49001. }
  49002. },
  49003. enumerable: true,
  49004. configurable: true
  49005. });
  49006. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49007. get: function () {
  49008. var keyboard = this.inputs.attached["keyboard"];
  49009. if (keyboard)
  49010. return keyboard.keysUp;
  49011. return [];
  49012. },
  49013. set: function (value) {
  49014. var keyboard = this.inputs.attached["keyboard"];
  49015. if (keyboard)
  49016. keyboard.keysUp = value;
  49017. },
  49018. enumerable: true,
  49019. configurable: true
  49020. });
  49021. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49022. get: function () {
  49023. var keyboard = this.inputs.attached["keyboard"];
  49024. if (keyboard)
  49025. return keyboard.keysDown;
  49026. return [];
  49027. },
  49028. set: function (value) {
  49029. var keyboard = this.inputs.attached["keyboard"];
  49030. if (keyboard)
  49031. keyboard.keysDown = value;
  49032. },
  49033. enumerable: true,
  49034. configurable: true
  49035. });
  49036. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49037. get: function () {
  49038. var keyboard = this.inputs.attached["keyboard"];
  49039. if (keyboard)
  49040. return keyboard.keysLeft;
  49041. return [];
  49042. },
  49043. set: function (value) {
  49044. var keyboard = this.inputs.attached["keyboard"];
  49045. if (keyboard)
  49046. keyboard.keysLeft = value;
  49047. },
  49048. enumerable: true,
  49049. configurable: true
  49050. });
  49051. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49052. get: function () {
  49053. var keyboard = this.inputs.attached["keyboard"];
  49054. if (keyboard)
  49055. return keyboard.keysRight;
  49056. return [];
  49057. },
  49058. set: function (value) {
  49059. var keyboard = this.inputs.attached["keyboard"];
  49060. if (keyboard)
  49061. keyboard.keysRight = value;
  49062. },
  49063. enumerable: true,
  49064. configurable: true
  49065. });
  49066. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49067. get: function () {
  49068. var mousewheel = this.inputs.attached["mousewheel"];
  49069. if (mousewheel)
  49070. return mousewheel.wheelPrecision;
  49071. return 0;
  49072. },
  49073. set: function (value) {
  49074. var mousewheel = this.inputs.attached["mousewheel"];
  49075. if (mousewheel)
  49076. mousewheel.wheelPrecision = value;
  49077. },
  49078. enumerable: true,
  49079. configurable: true
  49080. });
  49081. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49082. get: function () {
  49083. var mousewheel = this.inputs.attached["mousewheel"];
  49084. if (mousewheel)
  49085. return mousewheel.wheelDeltaPercentage;
  49086. return 0;
  49087. },
  49088. set: function (value) {
  49089. var mousewheel = this.inputs.attached["mousewheel"];
  49090. if (mousewheel)
  49091. mousewheel.wheelDeltaPercentage = value;
  49092. },
  49093. enumerable: true,
  49094. configurable: true
  49095. });
  49096. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49097. get: function () {
  49098. return this._bouncingBehavior;
  49099. },
  49100. enumerable: true,
  49101. configurable: true
  49102. });
  49103. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49104. get: function () {
  49105. return this._bouncingBehavior != null;
  49106. },
  49107. set: function (value) {
  49108. if (value === this.useBouncingBehavior) {
  49109. return;
  49110. }
  49111. if (value) {
  49112. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49113. this.addBehavior(this._bouncingBehavior);
  49114. }
  49115. else if (this._bouncingBehavior) {
  49116. this.removeBehavior(this._bouncingBehavior);
  49117. this._bouncingBehavior = null;
  49118. }
  49119. },
  49120. enumerable: true,
  49121. configurable: true
  49122. });
  49123. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49124. get: function () {
  49125. return this._framingBehavior;
  49126. },
  49127. enumerable: true,
  49128. configurable: true
  49129. });
  49130. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49131. get: function () {
  49132. return this._framingBehavior != null;
  49133. },
  49134. set: function (value) {
  49135. if (value === this.useFramingBehavior) {
  49136. return;
  49137. }
  49138. if (value) {
  49139. this._framingBehavior = new BABYLON.FramingBehavior();
  49140. this.addBehavior(this._framingBehavior);
  49141. }
  49142. else if (this._framingBehavior) {
  49143. this.removeBehavior(this._framingBehavior);
  49144. this._framingBehavior = null;
  49145. }
  49146. },
  49147. enumerable: true,
  49148. configurable: true
  49149. });
  49150. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49151. get: function () {
  49152. return this._autoRotationBehavior;
  49153. },
  49154. enumerable: true,
  49155. configurable: true
  49156. });
  49157. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49158. get: function () {
  49159. return this._autoRotationBehavior != null;
  49160. },
  49161. set: function (value) {
  49162. if (value === this.useAutoRotationBehavior) {
  49163. return;
  49164. }
  49165. if (value) {
  49166. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49167. this.addBehavior(this._autoRotationBehavior);
  49168. }
  49169. else if (this._autoRotationBehavior) {
  49170. this.removeBehavior(this._autoRotationBehavior);
  49171. this._autoRotationBehavior = null;
  49172. }
  49173. },
  49174. enumerable: true,
  49175. configurable: true
  49176. });
  49177. // Cache
  49178. ArcRotateCamera.prototype._initCache = function () {
  49179. _super.prototype._initCache.call(this);
  49180. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49181. this._cache.alpha = undefined;
  49182. this._cache.beta = undefined;
  49183. this._cache.radius = undefined;
  49184. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49185. };
  49186. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49187. if (!ignoreParentClass) {
  49188. _super.prototype._updateCache.call(this);
  49189. }
  49190. this._cache._target.copyFrom(this._getTargetPosition());
  49191. this._cache.alpha = this.alpha;
  49192. this._cache.beta = this.beta;
  49193. this._cache.radius = this.radius;
  49194. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49195. };
  49196. ArcRotateCamera.prototype._getTargetPosition = function () {
  49197. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49198. var pos = this._targetHost.getAbsolutePosition();
  49199. if (this._targetBoundingCenter) {
  49200. pos.addToRef(this._targetBoundingCenter, this._target);
  49201. }
  49202. else {
  49203. this._target.copyFrom(pos);
  49204. }
  49205. }
  49206. var lockedTargetPosition = this._getLockedTargetPosition();
  49207. if (lockedTargetPosition) {
  49208. return lockedTargetPosition;
  49209. }
  49210. return this._target;
  49211. };
  49212. ArcRotateCamera.prototype.storeState = function () {
  49213. this._storedAlpha = this.alpha;
  49214. this._storedBeta = this.beta;
  49215. this._storedRadius = this.radius;
  49216. this._storedTarget = this._getTargetPosition().clone();
  49217. return _super.prototype.storeState.call(this);
  49218. };
  49219. /**
  49220. * Restored camera state. You must call storeState() first
  49221. */
  49222. ArcRotateCamera.prototype._restoreStateValues = function () {
  49223. if (!_super.prototype._restoreStateValues.call(this)) {
  49224. return false;
  49225. }
  49226. this.alpha = this._storedAlpha;
  49227. this.beta = this._storedBeta;
  49228. this.radius = this._storedRadius;
  49229. this.setTarget(this._storedTarget.clone());
  49230. this.inertialAlphaOffset = 0;
  49231. this.inertialBetaOffset = 0;
  49232. this.inertialRadiusOffset = 0;
  49233. this.inertialPanningX = 0;
  49234. this.inertialPanningY = 0;
  49235. return true;
  49236. };
  49237. // Synchronized
  49238. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49239. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49240. return false;
  49241. return this._cache._target.equals(this._getTargetPosition())
  49242. && this._cache.alpha === this.alpha
  49243. && this._cache.beta === this.beta
  49244. && this._cache.radius === this.radius
  49245. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49246. };
  49247. // Methods
  49248. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49249. var _this = this;
  49250. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49251. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49252. this._useCtrlForPanning = useCtrlForPanning;
  49253. this._panningMouseButton = panningMouseButton;
  49254. this.inputs.attachElement(element, noPreventDefault);
  49255. this._reset = function () {
  49256. _this.inertialAlphaOffset = 0;
  49257. _this.inertialBetaOffset = 0;
  49258. _this.inertialRadiusOffset = 0;
  49259. _this.inertialPanningX = 0;
  49260. _this.inertialPanningY = 0;
  49261. };
  49262. };
  49263. ArcRotateCamera.prototype.detachControl = function (element) {
  49264. this.inputs.detachElement(element);
  49265. if (this._reset) {
  49266. this._reset();
  49267. }
  49268. };
  49269. ArcRotateCamera.prototype._checkInputs = function () {
  49270. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49271. if (this._collisionTriggered) {
  49272. return;
  49273. }
  49274. this.inputs.checkInputs();
  49275. // Inertia
  49276. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49277. var inertialAlphaOffset = this.inertialAlphaOffset;
  49278. if (this.beta <= 0)
  49279. inertialAlphaOffset *= -1;
  49280. if (this.getScene().useRightHandedSystem)
  49281. inertialAlphaOffset *= -1;
  49282. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49283. inertialAlphaOffset *= -1;
  49284. this.alpha += inertialAlphaOffset;
  49285. this.beta += this.inertialBetaOffset;
  49286. this.radius -= this.inertialRadiusOffset;
  49287. this.inertialAlphaOffset *= this.inertia;
  49288. this.inertialBetaOffset *= this.inertia;
  49289. this.inertialRadiusOffset *= this.inertia;
  49290. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49291. this.inertialAlphaOffset = 0;
  49292. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49293. this.inertialBetaOffset = 0;
  49294. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49295. this.inertialRadiusOffset = 0;
  49296. }
  49297. // Panning inertia
  49298. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49299. if (!this._localDirection) {
  49300. this._localDirection = BABYLON.Vector3.Zero();
  49301. this._transformedDirection = BABYLON.Vector3.Zero();
  49302. }
  49303. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49304. this._localDirection.multiplyInPlace(this.panningAxis);
  49305. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49306. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49307. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49308. if (!this.panningAxis.y) {
  49309. this._transformedDirection.y = 0;
  49310. }
  49311. if (!this._targetHost) {
  49312. if (this.panningDistanceLimit) {
  49313. this._transformedDirection.addInPlace(this._target);
  49314. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49315. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49316. this._target.copyFrom(this._transformedDirection);
  49317. }
  49318. }
  49319. else {
  49320. this._target.addInPlace(this._transformedDirection);
  49321. }
  49322. }
  49323. this.inertialPanningX *= this.panningInertia;
  49324. this.inertialPanningY *= this.panningInertia;
  49325. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49326. this.inertialPanningX = 0;
  49327. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49328. this.inertialPanningY = 0;
  49329. }
  49330. // Limits
  49331. this._checkLimits();
  49332. _super.prototype._checkInputs.call(this);
  49333. };
  49334. ArcRotateCamera.prototype._checkLimits = function () {
  49335. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49336. if (this.allowUpsideDown && this.beta > Math.PI) {
  49337. this.beta = this.beta - (2 * Math.PI);
  49338. }
  49339. }
  49340. else {
  49341. if (this.beta < this.lowerBetaLimit) {
  49342. this.beta = this.lowerBetaLimit;
  49343. }
  49344. }
  49345. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49346. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49347. this.beta = this.beta + (2 * Math.PI);
  49348. }
  49349. }
  49350. else {
  49351. if (this.beta > this.upperBetaLimit) {
  49352. this.beta = this.upperBetaLimit;
  49353. }
  49354. }
  49355. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49356. this.alpha = this.lowerAlphaLimit;
  49357. }
  49358. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49359. this.alpha = this.upperAlphaLimit;
  49360. }
  49361. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49362. this.radius = this.lowerRadiusLimit;
  49363. }
  49364. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49365. this.radius = this.upperRadiusLimit;
  49366. }
  49367. };
  49368. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49369. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49370. this.radius = this._computationVector.length();
  49371. if (this.radius === 0) {
  49372. this.radius = 0.0001; // Just to avoid division by zero
  49373. }
  49374. // Alpha
  49375. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49376. if (this._computationVector.z < 0) {
  49377. this.alpha = 2 * Math.PI - this.alpha;
  49378. }
  49379. // Beta
  49380. this.beta = Math.acos(this._computationVector.y / this.radius);
  49381. this._checkLimits();
  49382. };
  49383. ArcRotateCamera.prototype.setPosition = function (position) {
  49384. if (this.position.equals(position)) {
  49385. return;
  49386. }
  49387. this.position.copyFrom(position);
  49388. this.rebuildAnglesAndRadius();
  49389. };
  49390. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49391. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49392. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49393. if (target.getBoundingInfo) {
  49394. if (toBoundingCenter) {
  49395. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49396. }
  49397. else {
  49398. this._targetBoundingCenter = null;
  49399. }
  49400. this._targetHost = target;
  49401. this._target = this._getTargetPosition();
  49402. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49403. }
  49404. else {
  49405. var newTarget = target;
  49406. var currentTarget = this._getTargetPosition();
  49407. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49408. return;
  49409. }
  49410. this._targetHost = null;
  49411. this._target = newTarget;
  49412. this._targetBoundingCenter = null;
  49413. this.onMeshTargetChangedObservable.notifyObservers(null);
  49414. }
  49415. this.rebuildAnglesAndRadius();
  49416. };
  49417. ArcRotateCamera.prototype._getViewMatrix = function () {
  49418. // Compute
  49419. var cosa = Math.cos(this.alpha);
  49420. var sina = Math.sin(this.alpha);
  49421. var cosb = Math.cos(this.beta);
  49422. var sinb = Math.sin(this.beta);
  49423. if (sinb === 0) {
  49424. sinb = 0.0001;
  49425. }
  49426. var target = this._getTargetPosition();
  49427. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49428. target.addToRef(this._computationVector, this._newPosition);
  49429. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49430. if (!this._collider) {
  49431. this._collider = new BABYLON.Collider();
  49432. }
  49433. this._collider._radius = this.collisionRadius;
  49434. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49435. this._collisionTriggered = true;
  49436. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49437. }
  49438. else {
  49439. this.position.copyFrom(this._newPosition);
  49440. var up = this.upVector;
  49441. if (this.allowUpsideDown && sinb < 0) {
  49442. up = up.clone();
  49443. up = up.negate();
  49444. }
  49445. this._computeViewMatrix(this.position, target, up);
  49446. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49447. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49448. }
  49449. this._currentTarget = target;
  49450. return this._viewMatrix;
  49451. };
  49452. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49453. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49454. meshes = meshes || this.getScene().meshes;
  49455. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49456. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49457. this.radius = distance * this.zoomOnFactor;
  49458. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49459. };
  49460. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49461. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49462. var meshesOrMinMaxVector;
  49463. var distance;
  49464. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49465. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49466. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49467. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49468. }
  49469. else { //minMaxVector and distance
  49470. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49471. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49472. distance = minMaxVectorAndDistance.distance;
  49473. }
  49474. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49475. if (!doNotUpdateMaxZ) {
  49476. this.maxZ = distance * 2;
  49477. }
  49478. };
  49479. /**
  49480. * @override
  49481. * Override Camera.createRigCamera
  49482. */
  49483. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49484. var alphaShift = 0;
  49485. switch (this.cameraRigMode) {
  49486. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49487. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49488. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49489. case BABYLON.Camera.RIG_MODE_VR:
  49490. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49491. break;
  49492. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49493. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49494. break;
  49495. }
  49496. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49497. rigCam._cameraRigParams = {};
  49498. return rigCam;
  49499. };
  49500. /**
  49501. * @override
  49502. * Override Camera._updateRigCameras
  49503. */
  49504. ArcRotateCamera.prototype._updateRigCameras = function () {
  49505. var camLeft = this._rigCameras[0];
  49506. var camRight = this._rigCameras[1];
  49507. camLeft.beta = camRight.beta = this.beta;
  49508. camLeft.radius = camRight.radius = this.radius;
  49509. switch (this.cameraRigMode) {
  49510. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49511. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49512. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49513. case BABYLON.Camera.RIG_MODE_VR:
  49514. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49515. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49516. break;
  49517. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49518. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49519. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49520. break;
  49521. }
  49522. _super.prototype._updateRigCameras.call(this);
  49523. };
  49524. ArcRotateCamera.prototype.dispose = function () {
  49525. this.inputs.clear();
  49526. _super.prototype.dispose.call(this);
  49527. };
  49528. ArcRotateCamera.prototype.getClassName = function () {
  49529. return "ArcRotateCamera";
  49530. };
  49531. __decorate([
  49532. BABYLON.serialize()
  49533. ], ArcRotateCamera.prototype, "alpha", void 0);
  49534. __decorate([
  49535. BABYLON.serialize()
  49536. ], ArcRotateCamera.prototype, "beta", void 0);
  49537. __decorate([
  49538. BABYLON.serialize()
  49539. ], ArcRotateCamera.prototype, "radius", void 0);
  49540. __decorate([
  49541. BABYLON.serializeAsVector3("target")
  49542. ], ArcRotateCamera.prototype, "_target", void 0);
  49543. __decorate([
  49544. BABYLON.serialize()
  49545. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49546. __decorate([
  49547. BABYLON.serialize()
  49548. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49549. __decorate([
  49550. BABYLON.serialize()
  49551. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49552. __decorate([
  49553. BABYLON.serialize()
  49554. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49555. __decorate([
  49556. BABYLON.serialize()
  49557. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49558. __decorate([
  49559. BABYLON.serialize()
  49560. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49561. __decorate([
  49562. BABYLON.serialize()
  49563. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49564. __decorate([
  49565. BABYLON.serialize()
  49566. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49567. __decorate([
  49568. BABYLON.serialize()
  49569. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49570. __decorate([
  49571. BABYLON.serialize()
  49572. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49573. __decorate([
  49574. BABYLON.serialize()
  49575. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49576. __decorate([
  49577. BABYLON.serialize()
  49578. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49579. __decorate([
  49580. BABYLON.serialize()
  49581. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49582. __decorate([
  49583. BABYLON.serializeAsVector3()
  49584. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49585. __decorate([
  49586. BABYLON.serialize()
  49587. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49588. __decorate([
  49589. BABYLON.serialize()
  49590. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49591. __decorate([
  49592. BABYLON.serialize()
  49593. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49594. return ArcRotateCamera;
  49595. }(BABYLON.TargetCamera));
  49596. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49597. })(BABYLON || (BABYLON = {}));
  49598. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49599. var BABYLON;
  49600. (function (BABYLON) {
  49601. /**
  49602. * The HemisphericLight simulates the ambient environment light,
  49603. * so the passed direction is the light reflection direction, not the incoming direction.
  49604. */
  49605. var HemisphericLight = /** @class */ (function (_super) {
  49606. __extends(HemisphericLight, _super);
  49607. /**
  49608. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49609. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49610. * The HemisphericLight can't cast shadows.
  49611. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49612. * @param name The friendly name of the light
  49613. * @param direction The direction of the light reflection
  49614. * @param scene The scene the light belongs to
  49615. */
  49616. function HemisphericLight(name, direction, scene) {
  49617. var _this = _super.call(this, name, scene) || this;
  49618. /**
  49619. * The groundColor is the light in the opposite direction to the one specified during creation.
  49620. * 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.
  49621. */
  49622. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49623. _this.direction = direction || BABYLON.Vector3.Up();
  49624. return _this;
  49625. }
  49626. HemisphericLight.prototype._buildUniformLayout = function () {
  49627. this._uniformBuffer.addUniform("vLightData", 4);
  49628. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49629. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49630. this._uniformBuffer.addUniform("vLightGround", 3);
  49631. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49632. this._uniformBuffer.addUniform("depthValues", 2);
  49633. this._uniformBuffer.create();
  49634. };
  49635. /**
  49636. * Returns the string "HemisphericLight".
  49637. * @return The class name
  49638. */
  49639. HemisphericLight.prototype.getClassName = function () {
  49640. return "HemisphericLight";
  49641. };
  49642. /**
  49643. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49644. * Returns the updated direction.
  49645. * @param target The target the direction should point to
  49646. * @return The computed direction
  49647. */
  49648. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49649. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49650. return this.direction;
  49651. };
  49652. /**
  49653. * Returns the shadow generator associated to the light.
  49654. * @returns Always null for hemispheric lights because it does not support shadows.
  49655. */
  49656. HemisphericLight.prototype.getShadowGenerator = function () {
  49657. return null;
  49658. };
  49659. /**
  49660. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49661. * @param effect The effect to update
  49662. * @param lightIndex The index of the light in the effect to update
  49663. * @returns The hemispheric light
  49664. */
  49665. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49666. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49667. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49668. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49669. return this;
  49670. };
  49671. /**
  49672. * @hidden internal use only.
  49673. */
  49674. HemisphericLight.prototype._getWorldMatrix = function () {
  49675. if (!this._worldMatrix) {
  49676. this._worldMatrix = BABYLON.Matrix.Identity();
  49677. }
  49678. return this._worldMatrix;
  49679. };
  49680. /**
  49681. * Returns the integer 3.
  49682. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49683. */
  49684. HemisphericLight.prototype.getTypeID = function () {
  49685. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49686. };
  49687. __decorate([
  49688. BABYLON.serializeAsColor3()
  49689. ], HemisphericLight.prototype, "groundColor", void 0);
  49690. __decorate([
  49691. BABYLON.serializeAsVector3()
  49692. ], HemisphericLight.prototype, "direction", void 0);
  49693. return HemisphericLight;
  49694. }(BABYLON.Light));
  49695. BABYLON.HemisphericLight = HemisphericLight;
  49696. })(BABYLON || (BABYLON = {}));
  49697. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49698. var BABYLON;
  49699. (function (BABYLON) {
  49700. /**
  49701. * Base implementation IShadowLight
  49702. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49703. */
  49704. var ShadowLight = /** @class */ (function (_super) {
  49705. __extends(ShadowLight, _super);
  49706. function ShadowLight() {
  49707. var _this = _super !== null && _super.apply(this, arguments) || this;
  49708. _this._needProjectionMatrixCompute = true;
  49709. return _this;
  49710. }
  49711. ShadowLight.prototype._setPosition = function (value) {
  49712. this._position = value;
  49713. };
  49714. Object.defineProperty(ShadowLight.prototype, "position", {
  49715. /**
  49716. * Sets the position the shadow will be casted from. Also use as the light position for both
  49717. * point and spot lights.
  49718. */
  49719. get: function () {
  49720. return this._position;
  49721. },
  49722. /**
  49723. * Sets the position the shadow will be casted from. Also use as the light position for both
  49724. * point and spot lights.
  49725. */
  49726. set: function (value) {
  49727. this._setPosition(value);
  49728. },
  49729. enumerable: true,
  49730. configurable: true
  49731. });
  49732. ShadowLight.prototype._setDirection = function (value) {
  49733. this._direction = value;
  49734. };
  49735. Object.defineProperty(ShadowLight.prototype, "direction", {
  49736. /**
  49737. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49738. * Also use as the light direction on spot and directional lights.
  49739. */
  49740. get: function () {
  49741. return this._direction;
  49742. },
  49743. /**
  49744. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49745. * Also use as the light direction on spot and directional lights.
  49746. */
  49747. set: function (value) {
  49748. this._setDirection(value);
  49749. },
  49750. enumerable: true,
  49751. configurable: true
  49752. });
  49753. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49754. /**
  49755. * Gets the shadow projection clipping minimum z value.
  49756. */
  49757. get: function () {
  49758. return this._shadowMinZ;
  49759. },
  49760. /**
  49761. * Sets the shadow projection clipping minimum z value.
  49762. */
  49763. set: function (value) {
  49764. this._shadowMinZ = value;
  49765. this.forceProjectionMatrixCompute();
  49766. },
  49767. enumerable: true,
  49768. configurable: true
  49769. });
  49770. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49771. /**
  49772. * Sets the shadow projection clipping maximum z value.
  49773. */
  49774. get: function () {
  49775. return this._shadowMaxZ;
  49776. },
  49777. /**
  49778. * Gets the shadow projection clipping maximum z value.
  49779. */
  49780. set: function (value) {
  49781. this._shadowMaxZ = value;
  49782. this.forceProjectionMatrixCompute();
  49783. },
  49784. enumerable: true,
  49785. configurable: true
  49786. });
  49787. /**
  49788. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49789. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49790. */
  49791. ShadowLight.prototype.computeTransformedInformation = function () {
  49792. if (this.parent && this.parent.getWorldMatrix) {
  49793. if (!this.transformedPosition) {
  49794. this.transformedPosition = BABYLON.Vector3.Zero();
  49795. }
  49796. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49797. // In case the direction is present.
  49798. if (this.direction) {
  49799. if (!this.transformedDirection) {
  49800. this.transformedDirection = BABYLON.Vector3.Zero();
  49801. }
  49802. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49803. }
  49804. return true;
  49805. }
  49806. return false;
  49807. };
  49808. /**
  49809. * Return the depth scale used for the shadow map.
  49810. * @returns the depth scale.
  49811. */
  49812. ShadowLight.prototype.getDepthScale = function () {
  49813. return 50.0;
  49814. };
  49815. /**
  49816. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49817. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49818. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49819. */
  49820. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49821. return this.transformedDirection ? this.transformedDirection : this.direction;
  49822. };
  49823. /**
  49824. * Returns the ShadowLight absolute position in the World.
  49825. * @returns the position vector in world space
  49826. */
  49827. ShadowLight.prototype.getAbsolutePosition = function () {
  49828. return this.transformedPosition ? this.transformedPosition : this.position;
  49829. };
  49830. /**
  49831. * Sets the ShadowLight direction toward the passed target.
  49832. * @param target The point tot target in local space
  49833. * @returns the updated ShadowLight direction
  49834. */
  49835. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49836. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49837. return this.direction;
  49838. };
  49839. /**
  49840. * Returns the light rotation in euler definition.
  49841. * @returns the x y z rotation in local space.
  49842. */
  49843. ShadowLight.prototype.getRotation = function () {
  49844. this.direction.normalize();
  49845. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49846. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49847. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49848. };
  49849. /**
  49850. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49851. * @returns true if a cube texture needs to be use
  49852. */
  49853. ShadowLight.prototype.needCube = function () {
  49854. return false;
  49855. };
  49856. /**
  49857. * Detects if the projection matrix requires to be recomputed this frame.
  49858. * @returns true if it requires to be recomputed otherwise, false.
  49859. */
  49860. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49861. return this._needProjectionMatrixCompute;
  49862. };
  49863. /**
  49864. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49865. */
  49866. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49867. this._needProjectionMatrixCompute = true;
  49868. };
  49869. /**
  49870. * Get the world matrix of the sahdow lights.
  49871. * @hidden Internal Use Only
  49872. */
  49873. ShadowLight.prototype._getWorldMatrix = function () {
  49874. if (!this._worldMatrix) {
  49875. this._worldMatrix = BABYLON.Matrix.Identity();
  49876. }
  49877. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49878. return this._worldMatrix;
  49879. };
  49880. /**
  49881. * Gets the minZ used for shadow according to both the scene and the light.
  49882. * @param activeCamera The camera we are returning the min for
  49883. * @returns the depth min z
  49884. */
  49885. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49886. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49887. };
  49888. /**
  49889. * Gets the maxZ used for shadow according to both the scene and the light.
  49890. * @param activeCamera The camera we are returning the max for
  49891. * @returns the depth max z
  49892. */
  49893. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49894. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49895. };
  49896. /**
  49897. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49898. * @param matrix The materix to updated with the projection information
  49899. * @param viewMatrix The transform matrix of the light
  49900. * @param renderList The list of mesh to render in the map
  49901. * @returns The current light
  49902. */
  49903. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49904. if (this.customProjectionMatrixBuilder) {
  49905. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49906. }
  49907. else {
  49908. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49909. }
  49910. return this;
  49911. };
  49912. __decorate([
  49913. BABYLON.serializeAsVector3()
  49914. ], ShadowLight.prototype, "position", null);
  49915. __decorate([
  49916. BABYLON.serializeAsVector3()
  49917. ], ShadowLight.prototype, "direction", null);
  49918. __decorate([
  49919. BABYLON.serialize()
  49920. ], ShadowLight.prototype, "shadowMinZ", null);
  49921. __decorate([
  49922. BABYLON.serialize()
  49923. ], ShadowLight.prototype, "shadowMaxZ", null);
  49924. return ShadowLight;
  49925. }(BABYLON.Light));
  49926. BABYLON.ShadowLight = ShadowLight;
  49927. })(BABYLON || (BABYLON = {}));
  49928. //# sourceMappingURL=babylon.shadowLight.js.map
  49929. var BABYLON;
  49930. (function (BABYLON) {
  49931. /**
  49932. * A point light is a light defined by an unique point in world space.
  49933. * The light is emitted in every direction from this point.
  49934. * A good example of a point light is a standard light bulb.
  49935. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49936. */
  49937. var PointLight = /** @class */ (function (_super) {
  49938. __extends(PointLight, _super);
  49939. /**
  49940. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49941. * A PointLight emits the light in every direction.
  49942. * It can cast shadows.
  49943. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49944. * ```javascript
  49945. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49946. * ```
  49947. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49948. * @param name The light friendly name
  49949. * @param position The position of the point light in the scene
  49950. * @param scene The scene the lights belongs to
  49951. */
  49952. function PointLight(name, position, scene) {
  49953. var _this = _super.call(this, name, scene) || this;
  49954. _this._shadowAngle = Math.PI / 2;
  49955. _this.position = position;
  49956. return _this;
  49957. }
  49958. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49959. /**
  49960. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49961. * This specifies what angle the shadow will use to be created.
  49962. *
  49963. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49964. */
  49965. get: function () {
  49966. return this._shadowAngle;
  49967. },
  49968. /**
  49969. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49970. * This specifies what angle the shadow will use to be created.
  49971. *
  49972. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49973. */
  49974. set: function (value) {
  49975. this._shadowAngle = value;
  49976. this.forceProjectionMatrixCompute();
  49977. },
  49978. enumerable: true,
  49979. configurable: true
  49980. });
  49981. Object.defineProperty(PointLight.prototype, "direction", {
  49982. /**
  49983. * Gets the direction if it has been set.
  49984. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49985. */
  49986. get: function () {
  49987. return this._direction;
  49988. },
  49989. /**
  49990. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49991. */
  49992. set: function (value) {
  49993. var previousNeedCube = this.needCube();
  49994. this._direction = value;
  49995. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49996. this._shadowGenerator.recreateShadowMap();
  49997. }
  49998. },
  49999. enumerable: true,
  50000. configurable: true
  50001. });
  50002. /**
  50003. * Returns the string "PointLight"
  50004. * @returns the class name
  50005. */
  50006. PointLight.prototype.getClassName = function () {
  50007. return "PointLight";
  50008. };
  50009. /**
  50010. * Returns the integer 0.
  50011. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50012. */
  50013. PointLight.prototype.getTypeID = function () {
  50014. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50015. };
  50016. /**
  50017. * Specifies wether or not the shadowmap should be a cube texture.
  50018. * @returns true if the shadowmap needs to be a cube texture.
  50019. */
  50020. PointLight.prototype.needCube = function () {
  50021. return !this.direction;
  50022. };
  50023. /**
  50024. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50025. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50026. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50027. */
  50028. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50029. if (this.direction) {
  50030. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50031. }
  50032. else {
  50033. switch (faceIndex) {
  50034. case 0:
  50035. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50036. case 1:
  50037. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50038. case 2:
  50039. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50040. case 3:
  50041. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50042. case 4:
  50043. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50044. case 5:
  50045. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50046. }
  50047. }
  50048. return BABYLON.Vector3.Zero();
  50049. };
  50050. /**
  50051. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50052. * - fov = PI / 2
  50053. * - aspect ratio : 1.0
  50054. * - z-near and far equal to the active camera minZ and maxZ.
  50055. * Returns the PointLight.
  50056. */
  50057. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50058. var activeCamera = this.getScene().activeCamera;
  50059. if (!activeCamera) {
  50060. return;
  50061. }
  50062. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50063. };
  50064. PointLight.prototype._buildUniformLayout = function () {
  50065. this._uniformBuffer.addUniform("vLightData", 4);
  50066. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50067. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50068. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50069. this._uniformBuffer.addUniform("depthValues", 2);
  50070. this._uniformBuffer.create();
  50071. };
  50072. /**
  50073. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50074. * @param effect The effect to update
  50075. * @param lightIndex The index of the light in the effect to update
  50076. * @returns The point light
  50077. */
  50078. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50079. if (this.computeTransformedInformation()) {
  50080. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50081. return this;
  50082. }
  50083. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50084. return this;
  50085. };
  50086. __decorate([
  50087. BABYLON.serialize()
  50088. ], PointLight.prototype, "shadowAngle", null);
  50089. return PointLight;
  50090. }(BABYLON.ShadowLight));
  50091. BABYLON.PointLight = PointLight;
  50092. })(BABYLON || (BABYLON = {}));
  50093. //# sourceMappingURL=babylon.pointLight.js.map
  50094. var BABYLON;
  50095. (function (BABYLON) {
  50096. /**
  50097. * A directional light is defined by a direction (what a surprise!).
  50098. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50099. * 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.
  50100. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50101. */
  50102. var DirectionalLight = /** @class */ (function (_super) {
  50103. __extends(DirectionalLight, _super);
  50104. /**
  50105. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50106. * The directional light is emitted from everywhere in the given direction.
  50107. * It can cast shawdows.
  50108. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50109. * @param name The friendly name of the light
  50110. * @param direction The direction of the light
  50111. * @param scene The scene the light belongs to
  50112. */
  50113. function DirectionalLight(name, direction, scene) {
  50114. var _this = _super.call(this, name, scene) || this;
  50115. _this._shadowFrustumSize = 0;
  50116. _this._shadowOrthoScale = 0.1;
  50117. /**
  50118. * Automatically compute the projection matrix to best fit (including all the casters)
  50119. * on each frame.
  50120. */
  50121. _this.autoUpdateExtends = true;
  50122. // Cache
  50123. _this._orthoLeft = Number.MAX_VALUE;
  50124. _this._orthoRight = Number.MIN_VALUE;
  50125. _this._orthoTop = Number.MIN_VALUE;
  50126. _this._orthoBottom = Number.MAX_VALUE;
  50127. _this.position = direction.scale(-1.0);
  50128. _this.direction = direction;
  50129. return _this;
  50130. }
  50131. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50132. /**
  50133. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50134. */
  50135. get: function () {
  50136. return this._shadowFrustumSize;
  50137. },
  50138. /**
  50139. * Specifies a fix frustum size for the shadow generation.
  50140. */
  50141. set: function (value) {
  50142. this._shadowFrustumSize = value;
  50143. this.forceProjectionMatrixCompute();
  50144. },
  50145. enumerable: true,
  50146. configurable: true
  50147. });
  50148. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50149. /**
  50150. * Gets the shadow projection scale against the optimal computed one.
  50151. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50152. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50153. */
  50154. get: function () {
  50155. return this._shadowOrthoScale;
  50156. },
  50157. /**
  50158. * Sets the shadow projection scale against the optimal computed one.
  50159. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50160. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50161. */
  50162. set: function (value) {
  50163. this._shadowOrthoScale = value;
  50164. this.forceProjectionMatrixCompute();
  50165. },
  50166. enumerable: true,
  50167. configurable: true
  50168. });
  50169. /**
  50170. * Returns the string "DirectionalLight".
  50171. * @return The class name
  50172. */
  50173. DirectionalLight.prototype.getClassName = function () {
  50174. return "DirectionalLight";
  50175. };
  50176. /**
  50177. * Returns the integer 1.
  50178. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50179. */
  50180. DirectionalLight.prototype.getTypeID = function () {
  50181. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50182. };
  50183. /**
  50184. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50185. * Returns the DirectionalLight Shadow projection matrix.
  50186. */
  50187. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50188. if (this.shadowFrustumSize > 0) {
  50189. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50190. }
  50191. else {
  50192. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50193. }
  50194. };
  50195. /**
  50196. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50197. * Returns the DirectionalLight Shadow projection matrix.
  50198. */
  50199. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50200. var activeCamera = this.getScene().activeCamera;
  50201. if (!activeCamera) {
  50202. return;
  50203. }
  50204. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50205. };
  50206. /**
  50207. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50208. * Returns the DirectionalLight Shadow projection matrix.
  50209. */
  50210. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50211. var activeCamera = this.getScene().activeCamera;
  50212. if (!activeCamera) {
  50213. return;
  50214. }
  50215. // Check extends
  50216. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50217. var tempVector3 = BABYLON.Vector3.Zero();
  50218. this._orthoLeft = Number.MAX_VALUE;
  50219. this._orthoRight = Number.MIN_VALUE;
  50220. this._orthoTop = Number.MIN_VALUE;
  50221. this._orthoBottom = Number.MAX_VALUE;
  50222. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50223. var mesh = renderList[meshIndex];
  50224. if (!mesh) {
  50225. continue;
  50226. }
  50227. var boundingInfo = mesh.getBoundingInfo();
  50228. var boundingBox = boundingInfo.boundingBox;
  50229. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50230. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50231. if (tempVector3.x < this._orthoLeft)
  50232. this._orthoLeft = tempVector3.x;
  50233. if (tempVector3.y < this._orthoBottom)
  50234. this._orthoBottom = tempVector3.y;
  50235. if (tempVector3.x > this._orthoRight)
  50236. this._orthoRight = tempVector3.x;
  50237. if (tempVector3.y > this._orthoTop)
  50238. this._orthoTop = tempVector3.y;
  50239. }
  50240. }
  50241. }
  50242. var xOffset = this._orthoRight - this._orthoLeft;
  50243. var yOffset = this._orthoTop - this._orthoBottom;
  50244. 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);
  50245. };
  50246. DirectionalLight.prototype._buildUniformLayout = function () {
  50247. this._uniformBuffer.addUniform("vLightData", 4);
  50248. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50249. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50250. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50251. this._uniformBuffer.addUniform("depthValues", 2);
  50252. this._uniformBuffer.create();
  50253. };
  50254. /**
  50255. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50256. * @param effect The effect to update
  50257. * @param lightIndex The index of the light in the effect to update
  50258. * @returns The directional light
  50259. */
  50260. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50261. if (this.computeTransformedInformation()) {
  50262. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50263. return this;
  50264. }
  50265. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50266. return this;
  50267. };
  50268. /**
  50269. * Gets the minZ used for shadow according to both the scene and the light.
  50270. *
  50271. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50272. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50273. * @param activeCamera The camera we are returning the min for
  50274. * @returns the depth min z
  50275. */
  50276. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50277. return 1;
  50278. };
  50279. /**
  50280. * Gets the maxZ used for shadow according to both the scene and the light.
  50281. *
  50282. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50283. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50284. * @param activeCamera The camera we are returning the max for
  50285. * @returns the depth max z
  50286. */
  50287. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50288. return 1;
  50289. };
  50290. __decorate([
  50291. BABYLON.serialize()
  50292. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50293. __decorate([
  50294. BABYLON.serialize()
  50295. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50296. __decorate([
  50297. BABYLON.serialize()
  50298. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50299. return DirectionalLight;
  50300. }(BABYLON.ShadowLight));
  50301. BABYLON.DirectionalLight = DirectionalLight;
  50302. })(BABYLON || (BABYLON = {}));
  50303. //# sourceMappingURL=babylon.directionalLight.js.map
  50304. var BABYLON;
  50305. (function (BABYLON) {
  50306. /**
  50307. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50308. * These values define a cone of light starting from the position, emitting toward the direction.
  50309. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50310. * and the exponent defines the speed of the decay of the light with distance (reach).
  50311. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50312. */
  50313. var SpotLight = /** @class */ (function (_super) {
  50314. __extends(SpotLight, _super);
  50315. /**
  50316. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50317. * It can cast shadows.
  50318. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50319. * @param name The light friendly name
  50320. * @param position The position of the spot light in the scene
  50321. * @param direction The direction of the light in the scene
  50322. * @param angle The cone angle of the light in Radians
  50323. * @param exponent The light decay speed with the distance from the emission spot
  50324. * @param scene The scene the lights belongs to
  50325. */
  50326. function SpotLight(name, position, direction, angle, exponent, scene) {
  50327. var _this = _super.call(this, name, scene) || this;
  50328. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50329. _this._projectionTextureLightNear = 1e-6;
  50330. _this._projectionTextureLightFar = 1000.0;
  50331. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50332. _this._projectionTextureViewLightDirty = true;
  50333. _this._projectionTextureProjectionLightDirty = true;
  50334. _this._projectionTextureDirty = true;
  50335. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50336. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50337. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50338. _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);
  50339. _this.position = position;
  50340. _this.direction = direction;
  50341. _this.angle = angle;
  50342. _this.exponent = exponent;
  50343. return _this;
  50344. }
  50345. Object.defineProperty(SpotLight.prototype, "angle", {
  50346. /**
  50347. * Gets the cone angle of the spot light in Radians.
  50348. */
  50349. get: function () {
  50350. return this._angle;
  50351. },
  50352. /**
  50353. * Sets the cone angle of the spot light in Radians.
  50354. */
  50355. set: function (value) {
  50356. this._angle = value;
  50357. this._projectionTextureProjectionLightDirty = true;
  50358. this.forceProjectionMatrixCompute();
  50359. },
  50360. enumerable: true,
  50361. configurable: true
  50362. });
  50363. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50364. /**
  50365. * Allows scaling the angle of the light for shadow generation only.
  50366. */
  50367. get: function () {
  50368. return this._shadowAngleScale;
  50369. },
  50370. /**
  50371. * Allows scaling the angle of the light for shadow generation only.
  50372. */
  50373. set: function (value) {
  50374. this._shadowAngleScale = value;
  50375. this.forceProjectionMatrixCompute();
  50376. },
  50377. enumerable: true,
  50378. configurable: true
  50379. });
  50380. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50381. /**
  50382. * Allows reading the projecton texture
  50383. */
  50384. get: function () {
  50385. return this._projectionTextureMatrix;
  50386. },
  50387. enumerable: true,
  50388. configurable: true
  50389. });
  50390. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50391. /**
  50392. * Gets the near clip of the Spotlight for texture projection.
  50393. */
  50394. get: function () {
  50395. return this._projectionTextureLightNear;
  50396. },
  50397. /**
  50398. * Sets the near clip of the Spotlight for texture projection.
  50399. */
  50400. set: function (value) {
  50401. this._projectionTextureLightNear = value;
  50402. this._projectionTextureProjectionLightDirty = true;
  50403. },
  50404. enumerable: true,
  50405. configurable: true
  50406. });
  50407. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50408. /**
  50409. * Gets the far clip of the Spotlight for texture projection.
  50410. */
  50411. get: function () {
  50412. return this._projectionTextureLightFar;
  50413. },
  50414. /**
  50415. * Sets the far clip of the Spotlight for texture projection.
  50416. */
  50417. set: function (value) {
  50418. this._projectionTextureLightFar = value;
  50419. this._projectionTextureProjectionLightDirty = true;
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50425. /**
  50426. * Gets the Up vector of the Spotlight for texture projection.
  50427. */
  50428. get: function () {
  50429. return this._projectionTextureUpDirection;
  50430. },
  50431. /**
  50432. * Sets the Up vector of the Spotlight for texture projection.
  50433. */
  50434. set: function (value) {
  50435. this._projectionTextureUpDirection = value;
  50436. this._projectionTextureProjectionLightDirty = true;
  50437. },
  50438. enumerable: true,
  50439. configurable: true
  50440. });
  50441. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50442. /**
  50443. * Gets the projection texture of the light.
  50444. */
  50445. get: function () {
  50446. return this._projectionTexture;
  50447. },
  50448. /**
  50449. * Sets the projection texture of the light.
  50450. */
  50451. set: function (value) {
  50452. this._projectionTexture = value;
  50453. this._projectionTextureDirty = true;
  50454. },
  50455. enumerable: true,
  50456. configurable: true
  50457. });
  50458. /**
  50459. * Returns the string "SpotLight".
  50460. * @returns the class name
  50461. */
  50462. SpotLight.prototype.getClassName = function () {
  50463. return "SpotLight";
  50464. };
  50465. /**
  50466. * Returns the integer 2.
  50467. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50468. */
  50469. SpotLight.prototype.getTypeID = function () {
  50470. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50471. };
  50472. /**
  50473. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50474. */
  50475. SpotLight.prototype._setDirection = function (value) {
  50476. _super.prototype._setDirection.call(this, value);
  50477. this._projectionTextureViewLightDirty = true;
  50478. };
  50479. /**
  50480. * Overrides the position setter to recompute the projection texture view light Matrix.
  50481. */
  50482. SpotLight.prototype._setPosition = function (value) {
  50483. _super.prototype._setPosition.call(this, value);
  50484. this._projectionTextureViewLightDirty = true;
  50485. };
  50486. /**
  50487. * 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.
  50488. * Returns the SpotLight.
  50489. */
  50490. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50491. var activeCamera = this.getScene().activeCamera;
  50492. if (!activeCamera) {
  50493. return;
  50494. }
  50495. this._shadowAngleScale = this._shadowAngleScale || 1;
  50496. var angle = this._shadowAngleScale * this._angle;
  50497. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50498. };
  50499. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50500. this._projectionTextureViewLightDirty = false;
  50501. this._projectionTextureDirty = true;
  50502. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50503. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50504. };
  50505. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50506. this._projectionTextureProjectionLightDirty = false;
  50507. this._projectionTextureDirty = true;
  50508. var light_far = this.projectionTextureLightFar;
  50509. var light_near = this.projectionTextureLightNear;
  50510. var P = light_far / (light_far - light_near);
  50511. var Q = -P * light_near;
  50512. var S = 1.0 / Math.tan(this._angle / 2.0);
  50513. var A = 1.0;
  50514. 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);
  50515. };
  50516. /**
  50517. * Main function for light texture projection matrix computing.
  50518. */
  50519. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50520. this._projectionTextureDirty = false;
  50521. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50522. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50523. };
  50524. SpotLight.prototype._buildUniformLayout = function () {
  50525. this._uniformBuffer.addUniform("vLightData", 4);
  50526. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50527. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50528. this._uniformBuffer.addUniform("vLightDirection", 3);
  50529. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50530. this._uniformBuffer.addUniform("depthValues", 2);
  50531. this._uniformBuffer.create();
  50532. };
  50533. /**
  50534. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50535. * @param effect The effect to update
  50536. * @param lightIndex The index of the light in the effect to update
  50537. * @returns The spot light
  50538. */
  50539. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50540. var normalizeDirection;
  50541. if (this.computeTransformedInformation()) {
  50542. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50543. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50544. }
  50545. else {
  50546. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50547. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50548. }
  50549. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50550. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50551. if (this._projectionTextureViewLightDirty) {
  50552. this._computeProjectionTextureViewLightMatrix();
  50553. }
  50554. if (this._projectionTextureProjectionLightDirty) {
  50555. this._computeProjectionTextureProjectionLightMatrix();
  50556. }
  50557. if (this._projectionTextureDirty) {
  50558. this._computeProjectionTextureMatrix();
  50559. }
  50560. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50561. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50562. }
  50563. return this;
  50564. };
  50565. /**
  50566. * Disposes the light and the associated resources.
  50567. */
  50568. SpotLight.prototype.dispose = function () {
  50569. _super.prototype.dispose.call(this);
  50570. if (this._projectionTexture) {
  50571. this._projectionTexture.dispose();
  50572. }
  50573. };
  50574. __decorate([
  50575. BABYLON.serialize()
  50576. ], SpotLight.prototype, "angle", null);
  50577. __decorate([
  50578. BABYLON.serialize()
  50579. ], SpotLight.prototype, "shadowAngleScale", null);
  50580. __decorate([
  50581. BABYLON.serialize()
  50582. ], SpotLight.prototype, "exponent", void 0);
  50583. __decorate([
  50584. BABYLON.serialize()
  50585. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50586. __decorate([
  50587. BABYLON.serialize()
  50588. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50589. __decorate([
  50590. BABYLON.serialize()
  50591. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50592. __decorate([
  50593. BABYLON.serializeAsTexture("projectedLightTexture")
  50594. ], SpotLight.prototype, "_projectionTexture", void 0);
  50595. return SpotLight;
  50596. }(BABYLON.ShadowLight));
  50597. BABYLON.SpotLight = SpotLight;
  50598. })(BABYLON || (BABYLON = {}));
  50599. //# sourceMappingURL=babylon.spotLight.js.map
  50600. var BABYLON;
  50601. (function (BABYLON) {
  50602. /**
  50603. * Class used to override all child animations of a given target
  50604. */
  50605. var AnimationPropertiesOverride = /** @class */ (function () {
  50606. function AnimationPropertiesOverride() {
  50607. /**
  50608. * Gets or sets a value indicating if animation blending must be used
  50609. */
  50610. this.enableBlending = false;
  50611. /**
  50612. * Gets or sets the blending speed to use when enableBlending is true
  50613. */
  50614. this.blendingSpeed = 0.01;
  50615. /**
  50616. * Gets or sets the default loop mode to use
  50617. */
  50618. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50619. }
  50620. return AnimationPropertiesOverride;
  50621. }());
  50622. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50623. })(BABYLON || (BABYLON = {}));
  50624. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50625. var BABYLON;
  50626. (function (BABYLON) {
  50627. /**
  50628. * Represents the range of an animation
  50629. */
  50630. var AnimationRange = /** @class */ (function () {
  50631. /**
  50632. * Initializes the range of an animation
  50633. * @param name The name of the animation range
  50634. * @param from The starting frame of the animation
  50635. * @param to The ending frame of the animation
  50636. */
  50637. function AnimationRange(
  50638. /**The name of the animation range**/
  50639. name,
  50640. /**The starting frame of the animation */
  50641. from,
  50642. /**The ending frame of the animation*/
  50643. to) {
  50644. this.name = name;
  50645. this.from = from;
  50646. this.to = to;
  50647. }
  50648. /**
  50649. * Makes a copy of the animation range
  50650. * @returns A copy of the animation range
  50651. */
  50652. AnimationRange.prototype.clone = function () {
  50653. return new AnimationRange(this.name, this.from, this.to);
  50654. };
  50655. return AnimationRange;
  50656. }());
  50657. BABYLON.AnimationRange = AnimationRange;
  50658. /**
  50659. * Composed of a frame, and an action function
  50660. */
  50661. var AnimationEvent = /** @class */ (function () {
  50662. /**
  50663. * Initializes the animation event
  50664. * @param frame The frame for which the event is triggered
  50665. * @param action The event to perform when triggered
  50666. * @param onlyOnce Specifies if the event should be triggered only once
  50667. */
  50668. function AnimationEvent(
  50669. /** The frame for which the event is triggered **/
  50670. frame,
  50671. /** The event to perform when triggered **/
  50672. action,
  50673. /** Specifies if the event should be triggered only once**/
  50674. onlyOnce) {
  50675. this.frame = frame;
  50676. this.action = action;
  50677. this.onlyOnce = onlyOnce;
  50678. /**
  50679. * Specifies if the animation event is done
  50680. */
  50681. this.isDone = false;
  50682. }
  50683. /** @hidden */
  50684. AnimationEvent.prototype._clone = function () {
  50685. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50686. };
  50687. return AnimationEvent;
  50688. }());
  50689. BABYLON.AnimationEvent = AnimationEvent;
  50690. /**
  50691. * A cursor which tracks a point on a path
  50692. */
  50693. var PathCursor = /** @class */ (function () {
  50694. /**
  50695. * Initializes the path cursor
  50696. * @param path The path to track
  50697. */
  50698. function PathCursor(path) {
  50699. this.path = path;
  50700. /**
  50701. * Stores path cursor callbacks for when an onchange event is triggered
  50702. */
  50703. this._onchange = new Array();
  50704. /**
  50705. * The value of the path cursor
  50706. */
  50707. this.value = 0;
  50708. /**
  50709. * The animation array of the path cursor
  50710. */
  50711. this.animations = new Array();
  50712. }
  50713. /**
  50714. * Gets the cursor point on the path
  50715. * @returns A point on the path cursor at the cursor location
  50716. */
  50717. PathCursor.prototype.getPoint = function () {
  50718. var point = this.path.getPointAtLengthPosition(this.value);
  50719. return new BABYLON.Vector3(point.x, 0, point.y);
  50720. };
  50721. /**
  50722. * Moves the cursor ahead by the step amount
  50723. * @param step The amount to move the cursor forward
  50724. * @returns This path cursor
  50725. */
  50726. PathCursor.prototype.moveAhead = function (step) {
  50727. if (step === void 0) { step = 0.002; }
  50728. this.move(step);
  50729. return this;
  50730. };
  50731. /**
  50732. * Moves the cursor behind by the step amount
  50733. * @param step The amount to move the cursor back
  50734. * @returns This path cursor
  50735. */
  50736. PathCursor.prototype.moveBack = function (step) {
  50737. if (step === void 0) { step = 0.002; }
  50738. this.move(-step);
  50739. return this;
  50740. };
  50741. /**
  50742. * Moves the cursor by the step amount
  50743. * If the step amount is greater than one, an exception is thrown
  50744. * @param step The amount to move the cursor
  50745. * @returns This path cursor
  50746. */
  50747. PathCursor.prototype.move = function (step) {
  50748. if (Math.abs(step) > 1) {
  50749. throw "step size should be less than 1.";
  50750. }
  50751. this.value += step;
  50752. this.ensureLimits();
  50753. this.raiseOnChange();
  50754. return this;
  50755. };
  50756. /**
  50757. * Ensures that the value is limited between zero and one
  50758. * @returns This path cursor
  50759. */
  50760. PathCursor.prototype.ensureLimits = function () {
  50761. while (this.value > 1) {
  50762. this.value -= 1;
  50763. }
  50764. while (this.value < 0) {
  50765. this.value += 1;
  50766. }
  50767. return this;
  50768. };
  50769. /**
  50770. * Runs onchange callbacks on change (used by the animation engine)
  50771. * @returns This path cursor
  50772. */
  50773. PathCursor.prototype.raiseOnChange = function () {
  50774. var _this = this;
  50775. this._onchange.forEach(function (f) { return f(_this); });
  50776. return this;
  50777. };
  50778. /**
  50779. * Executes a function on change
  50780. * @param f A path cursor onchange callback
  50781. * @returns This path cursor
  50782. */
  50783. PathCursor.prototype.onchange = function (f) {
  50784. this._onchange.push(f);
  50785. return this;
  50786. };
  50787. return PathCursor;
  50788. }());
  50789. BABYLON.PathCursor = PathCursor;
  50790. /**
  50791. * Enum for the animation key frame interpolation type
  50792. */
  50793. var AnimationKeyInterpolation;
  50794. (function (AnimationKeyInterpolation) {
  50795. /**
  50796. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50797. */
  50798. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50799. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50800. /**
  50801. * Class used to store any kind of animation
  50802. */
  50803. var Animation = /** @class */ (function () {
  50804. /**
  50805. * Initializes the animation
  50806. * @param name Name of the animation
  50807. * @param targetProperty Property to animate
  50808. * @param framePerSecond The frames per second of the animation
  50809. * @param dataType The data type of the animation
  50810. * @param loopMode The loop mode of the animation
  50811. * @param enableBlendings Specifies if blending should be enabled
  50812. */
  50813. function Animation(
  50814. /**Name of the animation */
  50815. name,
  50816. /**Property to animate */
  50817. targetProperty,
  50818. /**The frames per second of the animation */
  50819. framePerSecond,
  50820. /**The data type of the animation */
  50821. dataType,
  50822. /**The loop mode of the animation */
  50823. loopMode,
  50824. /**Specifies if blending should be enabled */
  50825. enableBlending) {
  50826. this.name = name;
  50827. this.targetProperty = targetProperty;
  50828. this.framePerSecond = framePerSecond;
  50829. this.dataType = dataType;
  50830. this.loopMode = loopMode;
  50831. this.enableBlending = enableBlending;
  50832. /**
  50833. * @hidden Internal use only
  50834. */
  50835. this._runtimeAnimations = new Array();
  50836. /**
  50837. * The set of event that will be linked to this animation
  50838. */
  50839. this._events = new Array();
  50840. /**
  50841. * Stores the blending speed of the animation
  50842. */
  50843. this.blendingSpeed = 0.01;
  50844. /**
  50845. * Stores the animation ranges for the animation
  50846. */
  50847. this._ranges = {};
  50848. this.targetPropertyPath = targetProperty.split(".");
  50849. this.dataType = dataType;
  50850. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50851. }
  50852. /**
  50853. * @hidden Internal use
  50854. */
  50855. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50856. var dataType = undefined;
  50857. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50858. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50859. }
  50860. else if (from instanceof BABYLON.Quaternion) {
  50861. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50862. }
  50863. else if (from instanceof BABYLON.Vector3) {
  50864. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50865. }
  50866. else if (from instanceof BABYLON.Vector2) {
  50867. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50868. }
  50869. else if (from instanceof BABYLON.Color3) {
  50870. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50871. }
  50872. else if (from instanceof BABYLON.Size) {
  50873. dataType = Animation.ANIMATIONTYPE_SIZE;
  50874. }
  50875. if (dataType == undefined) {
  50876. return null;
  50877. }
  50878. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50879. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50880. animation.setKeys(keys);
  50881. if (easingFunction !== undefined) {
  50882. animation.setEasingFunction(easingFunction);
  50883. }
  50884. return animation;
  50885. };
  50886. /**
  50887. * Sets up an animation
  50888. * @param property The property to animate
  50889. * @param animationType The animation type to apply
  50890. * @param framePerSecond The frames per second of the animation
  50891. * @param easingFunction The easing function used in the animation
  50892. * @returns The created animation
  50893. */
  50894. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50895. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50896. animation.setEasingFunction(easingFunction);
  50897. return animation;
  50898. };
  50899. /**
  50900. * Create and start an animation on a node
  50901. * @param name defines the name of the global animation that will be run on all nodes
  50902. * @param node defines the root node where the animation will take place
  50903. * @param targetProperty defines property to animate
  50904. * @param framePerSecond defines the number of frame per second yo use
  50905. * @param totalFrame defines the number of frames in total
  50906. * @param from defines the initial value
  50907. * @param to defines the final value
  50908. * @param loopMode defines which loop mode you want to use (off by default)
  50909. * @param easingFunction defines the easing function to use (linear by default)
  50910. * @param onAnimationEnd defines the callback to call when animation end
  50911. * @returns the animatable created for this animation
  50912. */
  50913. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50914. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50915. if (!animation) {
  50916. return null;
  50917. }
  50918. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50919. };
  50920. /**
  50921. * Create and start an animation on a node and its descendants
  50922. * @param name defines the name of the global animation that will be run on all nodes
  50923. * @param node defines the root node where the animation will take place
  50924. * @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
  50925. * @param targetProperty defines property to animate
  50926. * @param framePerSecond defines the number of frame per second to use
  50927. * @param totalFrame defines the number of frames in total
  50928. * @param from defines the initial value
  50929. * @param to defines the final value
  50930. * @param loopMode defines which loop mode you want to use (off by default)
  50931. * @param easingFunction defines the easing function to use (linear by default)
  50932. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50933. * @returns the list of animatables created for all nodes
  50934. * @example https://www.babylonjs-playground.com/#MH0VLI
  50935. */
  50936. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50937. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50938. if (!animation) {
  50939. return null;
  50940. }
  50941. var scene = node.getScene();
  50942. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50943. };
  50944. /**
  50945. * Creates a new animation, merges it with the existing animations and starts it
  50946. * @param name Name of the animation
  50947. * @param node Node which contains the scene that begins the animations
  50948. * @param targetProperty Specifies which property to animate
  50949. * @param framePerSecond The frames per second of the animation
  50950. * @param totalFrame The total number of frames
  50951. * @param from The frame at the beginning of the animation
  50952. * @param to The frame at the end of the animation
  50953. * @param loopMode Specifies the loop mode of the animation
  50954. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50955. * @param onAnimationEnd Callback to run once the animation is complete
  50956. * @returns Nullable animation
  50957. */
  50958. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50959. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50960. if (!animation) {
  50961. return null;
  50962. }
  50963. node.animations.push(animation);
  50964. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50965. };
  50966. /**
  50967. * Transition property of an host to the target Value
  50968. * @param property The property to transition
  50969. * @param targetValue The target Value of the property
  50970. * @param host The object where the property to animate belongs
  50971. * @param scene Scene used to run the animation
  50972. * @param frameRate Framerate (in frame/s) to use
  50973. * @param transition The transition type we want to use
  50974. * @param duration The duration of the animation, in milliseconds
  50975. * @param onAnimationEnd Callback trigger at the end of the animation
  50976. * @returns Nullable animation
  50977. */
  50978. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50979. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50980. if (duration <= 0) {
  50981. host[property] = targetValue;
  50982. if (onAnimationEnd) {
  50983. onAnimationEnd();
  50984. }
  50985. return null;
  50986. }
  50987. var endFrame = frameRate * (duration / 1000);
  50988. transition.setKeys([{
  50989. frame: 0,
  50990. value: host[property].clone ? host[property].clone() : host[property]
  50991. },
  50992. {
  50993. frame: endFrame,
  50994. value: targetValue
  50995. }]);
  50996. if (!host.animations) {
  50997. host.animations = [];
  50998. }
  50999. host.animations.push(transition);
  51000. var animation = scene.beginAnimation(host, 0, endFrame, false);
  51001. animation.onAnimationEnd = onAnimationEnd;
  51002. return animation;
  51003. };
  51004. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  51005. /**
  51006. * Return the array of runtime animations currently using this animation
  51007. */
  51008. get: function () {
  51009. return this._runtimeAnimations;
  51010. },
  51011. enumerable: true,
  51012. configurable: true
  51013. });
  51014. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51015. /**
  51016. * Specifies if any of the runtime animations are currently running
  51017. */
  51018. get: function () {
  51019. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51020. var runtimeAnimation = _a[_i];
  51021. if (!runtimeAnimation.isStopped) {
  51022. return true;
  51023. }
  51024. }
  51025. return false;
  51026. },
  51027. enumerable: true,
  51028. configurable: true
  51029. });
  51030. // Methods
  51031. /**
  51032. * Converts the animation to a string
  51033. * @param fullDetails support for multiple levels of logging within scene loading
  51034. * @returns String form of the animation
  51035. */
  51036. Animation.prototype.toString = function (fullDetails) {
  51037. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51038. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51039. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51040. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51041. if (fullDetails) {
  51042. ret += ", Ranges: {";
  51043. var first = true;
  51044. for (var name in this._ranges) {
  51045. if (first) {
  51046. ret += ", ";
  51047. first = false;
  51048. }
  51049. ret += name;
  51050. }
  51051. ret += "}";
  51052. }
  51053. return ret;
  51054. };
  51055. /**
  51056. * Add an event to this animation
  51057. * @param event Event to add
  51058. */
  51059. Animation.prototype.addEvent = function (event) {
  51060. this._events.push(event);
  51061. };
  51062. /**
  51063. * Remove all events found at the given frame
  51064. * @param frame The frame to remove events from
  51065. */
  51066. Animation.prototype.removeEvents = function (frame) {
  51067. for (var index = 0; index < this._events.length; index++) {
  51068. if (this._events[index].frame === frame) {
  51069. this._events.splice(index, 1);
  51070. index--;
  51071. }
  51072. }
  51073. };
  51074. /**
  51075. * Retrieves all the events from the animation
  51076. * @returns Events from the animation
  51077. */
  51078. Animation.prototype.getEvents = function () {
  51079. return this._events;
  51080. };
  51081. /**
  51082. * Creates an animation range
  51083. * @param name Name of the animation range
  51084. * @param from Starting frame of the animation range
  51085. * @param to Ending frame of the animation
  51086. */
  51087. Animation.prototype.createRange = function (name, from, to) {
  51088. // check name not already in use; could happen for bones after serialized
  51089. if (!this._ranges[name]) {
  51090. this._ranges[name] = new AnimationRange(name, from, to);
  51091. }
  51092. };
  51093. /**
  51094. * Deletes an animation range by name
  51095. * @param name Name of the animation range to delete
  51096. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51097. */
  51098. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51099. if (deleteFrames === void 0) { deleteFrames = true; }
  51100. var range = this._ranges[name];
  51101. if (!range) {
  51102. return;
  51103. }
  51104. if (deleteFrames) {
  51105. var from = range.from;
  51106. var to = range.to;
  51107. // this loop MUST go high to low for multiple splices to work
  51108. for (var key = this._keys.length - 1; key >= 0; key--) {
  51109. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51110. this._keys.splice(key, 1);
  51111. }
  51112. }
  51113. }
  51114. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51115. };
  51116. /**
  51117. * Gets the animation range by name, or null if not defined
  51118. * @param name Name of the animation range
  51119. * @returns Nullable animation range
  51120. */
  51121. Animation.prototype.getRange = function (name) {
  51122. return this._ranges[name];
  51123. };
  51124. /**
  51125. * Gets the key frames from the animation
  51126. * @returns The key frames of the animation
  51127. */
  51128. Animation.prototype.getKeys = function () {
  51129. return this._keys;
  51130. };
  51131. /**
  51132. * Gets the highest frame rate of the animation
  51133. * @returns Highest frame rate of the animation
  51134. */
  51135. Animation.prototype.getHighestFrame = function () {
  51136. var ret = 0;
  51137. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51138. if (ret < this._keys[key].frame) {
  51139. ret = this._keys[key].frame;
  51140. }
  51141. }
  51142. return ret;
  51143. };
  51144. /**
  51145. * Gets the easing function of the animation
  51146. * @returns Easing function of the animation
  51147. */
  51148. Animation.prototype.getEasingFunction = function () {
  51149. return this._easingFunction;
  51150. };
  51151. /**
  51152. * Sets the easing function of the animation
  51153. * @param easingFunction A custom mathematical formula for animation
  51154. */
  51155. Animation.prototype.setEasingFunction = function (easingFunction) {
  51156. this._easingFunction = easingFunction;
  51157. };
  51158. /**
  51159. * Interpolates a scalar linearly
  51160. * @param startValue Start value of the animation curve
  51161. * @param endValue End value of the animation curve
  51162. * @param gradient Scalar amount to interpolate
  51163. * @returns Interpolated scalar value
  51164. */
  51165. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51166. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51167. };
  51168. /**
  51169. * Interpolates a scalar cubically
  51170. * @param startValue Start value of the animation curve
  51171. * @param outTangent End tangent of the animation
  51172. * @param endValue End value of the animation curve
  51173. * @param inTangent Start tangent of the animation curve
  51174. * @param gradient Scalar amount to interpolate
  51175. * @returns Interpolated scalar value
  51176. */
  51177. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51178. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51179. };
  51180. /**
  51181. * Interpolates a quaternion using a spherical linear interpolation
  51182. * @param startValue Start value of the animation curve
  51183. * @param endValue End value of the animation curve
  51184. * @param gradient Scalar amount to interpolate
  51185. * @returns Interpolated quaternion value
  51186. */
  51187. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51188. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51189. };
  51190. /**
  51191. * Interpolates a quaternion cubically
  51192. * @param startValue Start value of the animation curve
  51193. * @param outTangent End tangent of the animation curve
  51194. * @param endValue End value of the animation curve
  51195. * @param inTangent Start tangent of the animation curve
  51196. * @param gradient Scalar amount to interpolate
  51197. * @returns Interpolated quaternion value
  51198. */
  51199. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51200. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51201. };
  51202. /**
  51203. * Interpolates a Vector3 linearl
  51204. * @param startValue Start value of the animation curve
  51205. * @param endValue End value of the animation curve
  51206. * @param gradient Scalar amount to interpolate
  51207. * @returns Interpolated scalar value
  51208. */
  51209. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51210. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51211. };
  51212. /**
  51213. * Interpolates a Vector3 cubically
  51214. * @param startValue Start value of the animation curve
  51215. * @param outTangent End tangent of the animation
  51216. * @param endValue End value of the animation curve
  51217. * @param inTangent Start tangent of the animation curve
  51218. * @param gradient Scalar amount to interpolate
  51219. * @returns InterpolatedVector3 value
  51220. */
  51221. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51222. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51223. };
  51224. /**
  51225. * Interpolates a Vector2 linearly
  51226. * @param startValue Start value of the animation curve
  51227. * @param endValue End value of the animation curve
  51228. * @param gradient Scalar amount to interpolate
  51229. * @returns Interpolated Vector2 value
  51230. */
  51231. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51232. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51233. };
  51234. /**
  51235. * Interpolates a Vector2 cubically
  51236. * @param startValue Start value of the animation curve
  51237. * @param outTangent End tangent of the animation
  51238. * @param endValue End value of the animation curve
  51239. * @param inTangent Start tangent of the animation curve
  51240. * @param gradient Scalar amount to interpolate
  51241. * @returns Interpolated Vector2 value
  51242. */
  51243. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51244. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51245. };
  51246. /**
  51247. * Interpolates a size linearly
  51248. * @param startValue Start value of the animation curve
  51249. * @param endValue End value of the animation curve
  51250. * @param gradient Scalar amount to interpolate
  51251. * @returns Interpolated Size value
  51252. */
  51253. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51254. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51255. };
  51256. /**
  51257. * Interpolates a Color3 linearly
  51258. * @param startValue Start value of the animation curve
  51259. * @param endValue End value of the animation curve
  51260. * @param gradient Scalar amount to interpolate
  51261. * @returns Interpolated Color3 value
  51262. */
  51263. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51264. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51265. };
  51266. /**
  51267. * @hidden Internal use only
  51268. */
  51269. Animation.prototype._getKeyValue = function (value) {
  51270. if (typeof value === "function") {
  51271. return value();
  51272. }
  51273. return value;
  51274. };
  51275. /**
  51276. * @hidden Internal use only
  51277. */
  51278. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51279. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51280. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51281. }
  51282. var keys = this.getKeys();
  51283. // Try to get a hash to find the right key
  51284. 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));
  51285. if (keys[startKeyIndex].frame >= currentFrame) {
  51286. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51287. startKeyIndex--;
  51288. }
  51289. }
  51290. for (var key = startKeyIndex; key < keys.length; key++) {
  51291. var endKey = keys[key + 1];
  51292. if (endKey.frame >= currentFrame) {
  51293. var startKey = keys[key];
  51294. var startValue = this._getKeyValue(startKey.value);
  51295. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51296. return startValue;
  51297. }
  51298. var endValue = this._getKeyValue(endKey.value);
  51299. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51300. var frameDelta = endKey.frame - startKey.frame;
  51301. // gradient : percent of currentFrame between the frame inf and the frame sup
  51302. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51303. // check for easingFunction and correction of gradient
  51304. var easingFunction = this.getEasingFunction();
  51305. if (easingFunction != null) {
  51306. gradient = easingFunction.ease(gradient);
  51307. }
  51308. switch (this.dataType) {
  51309. // Float
  51310. case Animation.ANIMATIONTYPE_FLOAT:
  51311. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51312. switch (loopMode) {
  51313. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51314. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51315. return floatValue;
  51316. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51317. return offsetValue * repeatCount + floatValue;
  51318. }
  51319. break;
  51320. // Quaternion
  51321. case Animation.ANIMATIONTYPE_QUATERNION:
  51322. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51323. switch (loopMode) {
  51324. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51325. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51326. return quatValue;
  51327. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51328. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51329. }
  51330. return quatValue;
  51331. // Vector3
  51332. case Animation.ANIMATIONTYPE_VECTOR3:
  51333. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51334. switch (loopMode) {
  51335. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51336. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51337. return vec3Value;
  51338. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51339. return vec3Value.add(offsetValue.scale(repeatCount));
  51340. }
  51341. // Vector2
  51342. case Animation.ANIMATIONTYPE_VECTOR2:
  51343. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51344. switch (loopMode) {
  51345. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51346. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51347. return vec2Value;
  51348. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51349. return vec2Value.add(offsetValue.scale(repeatCount));
  51350. }
  51351. // Size
  51352. case Animation.ANIMATIONTYPE_SIZE:
  51353. switch (loopMode) {
  51354. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51355. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51356. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51357. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51358. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51359. }
  51360. // Color3
  51361. case Animation.ANIMATIONTYPE_COLOR3:
  51362. switch (loopMode) {
  51363. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51364. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51365. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51366. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51367. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51368. }
  51369. // Matrix
  51370. case Animation.ANIMATIONTYPE_MATRIX:
  51371. switch (loopMode) {
  51372. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51373. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51374. if (Animation.AllowMatricesInterpolation) {
  51375. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51376. }
  51377. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51378. return startValue;
  51379. }
  51380. default:
  51381. break;
  51382. }
  51383. break;
  51384. }
  51385. }
  51386. return this._getKeyValue(keys[keys.length - 1].value);
  51387. };
  51388. /**
  51389. * Defines the function to use to interpolate matrices
  51390. * @param startValue defines the start matrix
  51391. * @param endValue defines the end matrix
  51392. * @param gradient defines the gradient between both matrices
  51393. * @param result defines an optional target matrix where to store the interpolation
  51394. * @returns the interpolated matrix
  51395. */
  51396. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51397. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51398. if (result) {
  51399. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51400. return result;
  51401. }
  51402. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51403. }
  51404. if (result) {
  51405. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51406. return result;
  51407. }
  51408. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51409. };
  51410. /**
  51411. * Makes a copy of the animation
  51412. * @returns Cloned animation
  51413. */
  51414. Animation.prototype.clone = function () {
  51415. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51416. clone.enableBlending = this.enableBlending;
  51417. clone.blendingSpeed = this.blendingSpeed;
  51418. if (this._keys) {
  51419. clone.setKeys(this._keys);
  51420. }
  51421. if (this._ranges) {
  51422. clone._ranges = {};
  51423. for (var name in this._ranges) {
  51424. var range = this._ranges[name];
  51425. if (!range) {
  51426. continue;
  51427. }
  51428. clone._ranges[name] = range.clone();
  51429. }
  51430. }
  51431. return clone;
  51432. };
  51433. /**
  51434. * Sets the key frames of the animation
  51435. * @param values The animation key frames to set
  51436. */
  51437. Animation.prototype.setKeys = function (values) {
  51438. this._keys = values.slice(0);
  51439. };
  51440. /**
  51441. * Serializes the animation to an object
  51442. * @returns Serialized object
  51443. */
  51444. Animation.prototype.serialize = function () {
  51445. var serializationObject = {};
  51446. serializationObject.name = this.name;
  51447. serializationObject.property = this.targetProperty;
  51448. serializationObject.framePerSecond = this.framePerSecond;
  51449. serializationObject.dataType = this.dataType;
  51450. serializationObject.loopBehavior = this.loopMode;
  51451. serializationObject.enableBlending = this.enableBlending;
  51452. serializationObject.blendingSpeed = this.blendingSpeed;
  51453. var dataType = this.dataType;
  51454. serializationObject.keys = [];
  51455. var keys = this.getKeys();
  51456. for (var index = 0; index < keys.length; index++) {
  51457. var animationKey = keys[index];
  51458. var key = {};
  51459. key.frame = animationKey.frame;
  51460. switch (dataType) {
  51461. case Animation.ANIMATIONTYPE_FLOAT:
  51462. key.values = [animationKey.value];
  51463. break;
  51464. case Animation.ANIMATIONTYPE_QUATERNION:
  51465. case Animation.ANIMATIONTYPE_MATRIX:
  51466. case Animation.ANIMATIONTYPE_VECTOR3:
  51467. case Animation.ANIMATIONTYPE_COLOR3:
  51468. key.values = animationKey.value.asArray();
  51469. break;
  51470. }
  51471. serializationObject.keys.push(key);
  51472. }
  51473. serializationObject.ranges = [];
  51474. for (var name in this._ranges) {
  51475. var source = this._ranges[name];
  51476. if (!source) {
  51477. continue;
  51478. }
  51479. var range = {};
  51480. range.name = name;
  51481. range.from = source.from;
  51482. range.to = source.to;
  51483. serializationObject.ranges.push(range);
  51484. }
  51485. return serializationObject;
  51486. };
  51487. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51488. /**
  51489. * Get the float animation type
  51490. */
  51491. get: function () {
  51492. return Animation._ANIMATIONTYPE_FLOAT;
  51493. },
  51494. enumerable: true,
  51495. configurable: true
  51496. });
  51497. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51498. /**
  51499. * Get the Vector3 animation type
  51500. */
  51501. get: function () {
  51502. return Animation._ANIMATIONTYPE_VECTOR3;
  51503. },
  51504. enumerable: true,
  51505. configurable: true
  51506. });
  51507. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51508. /**
  51509. * Get the Vectpr2 animation type
  51510. */
  51511. get: function () {
  51512. return Animation._ANIMATIONTYPE_VECTOR2;
  51513. },
  51514. enumerable: true,
  51515. configurable: true
  51516. });
  51517. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51518. /**
  51519. * Get the Size animation type
  51520. */
  51521. get: function () {
  51522. return Animation._ANIMATIONTYPE_SIZE;
  51523. },
  51524. enumerable: true,
  51525. configurable: true
  51526. });
  51527. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51528. /**
  51529. * Get the Quaternion animation type
  51530. */
  51531. get: function () {
  51532. return Animation._ANIMATIONTYPE_QUATERNION;
  51533. },
  51534. enumerable: true,
  51535. configurable: true
  51536. });
  51537. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51538. /**
  51539. * Get the Matrix animation type
  51540. */
  51541. get: function () {
  51542. return Animation._ANIMATIONTYPE_MATRIX;
  51543. },
  51544. enumerable: true,
  51545. configurable: true
  51546. });
  51547. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51548. /**
  51549. * Get the Color3 animation type
  51550. */
  51551. get: function () {
  51552. return Animation._ANIMATIONTYPE_COLOR3;
  51553. },
  51554. enumerable: true,
  51555. configurable: true
  51556. });
  51557. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51558. /**
  51559. * Get the Relative Loop Mode
  51560. */
  51561. get: function () {
  51562. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51563. },
  51564. enumerable: true,
  51565. configurable: true
  51566. });
  51567. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51568. /**
  51569. * Get the Cycle Loop Mode
  51570. */
  51571. get: function () {
  51572. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51573. },
  51574. enumerable: true,
  51575. configurable: true
  51576. });
  51577. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51578. /**
  51579. * Get the Constant Loop Mode
  51580. */
  51581. get: function () {
  51582. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51583. },
  51584. enumerable: true,
  51585. configurable: true
  51586. });
  51587. /** @hidden */
  51588. Animation._UniversalLerp = function (left, right, amount) {
  51589. var constructor = left.constructor;
  51590. if (constructor.Lerp) { // Lerp supported
  51591. return constructor.Lerp(left, right, amount);
  51592. }
  51593. else if (constructor.Slerp) { // Slerp supported
  51594. return constructor.Slerp(left, right, amount);
  51595. }
  51596. else if (left.toFixed) { // Number
  51597. return left * (1.0 - amount) + amount * right;
  51598. }
  51599. else { // Blending not supported
  51600. return right;
  51601. }
  51602. };
  51603. /**
  51604. * Parses an animation object and creates an animation
  51605. * @param parsedAnimation Parsed animation object
  51606. * @returns Animation object
  51607. */
  51608. Animation.Parse = function (parsedAnimation) {
  51609. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51610. var dataType = parsedAnimation.dataType;
  51611. var keys = [];
  51612. var data;
  51613. var index;
  51614. if (parsedAnimation.enableBlending) {
  51615. animation.enableBlending = parsedAnimation.enableBlending;
  51616. }
  51617. if (parsedAnimation.blendingSpeed) {
  51618. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51619. }
  51620. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51621. var key = parsedAnimation.keys[index];
  51622. var inTangent;
  51623. var outTangent;
  51624. switch (dataType) {
  51625. case Animation.ANIMATIONTYPE_FLOAT:
  51626. data = key.values[0];
  51627. if (key.values.length >= 1) {
  51628. inTangent = key.values[1];
  51629. }
  51630. if (key.values.length >= 2) {
  51631. outTangent = key.values[2];
  51632. }
  51633. break;
  51634. case Animation.ANIMATIONTYPE_QUATERNION:
  51635. data = BABYLON.Quaternion.FromArray(key.values);
  51636. if (key.values.length >= 8) {
  51637. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51638. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51639. inTangent = _inTangent;
  51640. }
  51641. }
  51642. if (key.values.length >= 12) {
  51643. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51644. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51645. outTangent = _outTangent;
  51646. }
  51647. }
  51648. break;
  51649. case Animation.ANIMATIONTYPE_MATRIX:
  51650. data = BABYLON.Matrix.FromArray(key.values);
  51651. break;
  51652. case Animation.ANIMATIONTYPE_COLOR3:
  51653. data = BABYLON.Color3.FromArray(key.values);
  51654. break;
  51655. case Animation.ANIMATIONTYPE_VECTOR3:
  51656. default:
  51657. data = BABYLON.Vector3.FromArray(key.values);
  51658. break;
  51659. }
  51660. var keyData = {};
  51661. keyData.frame = key.frame;
  51662. keyData.value = data;
  51663. if (inTangent != undefined) {
  51664. keyData.inTangent = inTangent;
  51665. }
  51666. if (outTangent != undefined) {
  51667. keyData.outTangent = outTangent;
  51668. }
  51669. keys.push(keyData);
  51670. }
  51671. animation.setKeys(keys);
  51672. if (parsedAnimation.ranges) {
  51673. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51674. data = parsedAnimation.ranges[index];
  51675. animation.createRange(data.name, data.from, data.to);
  51676. }
  51677. }
  51678. return animation;
  51679. };
  51680. /**
  51681. * Appends the serialized animations from the source animations
  51682. * @param source Source containing the animations
  51683. * @param destination Target to store the animations
  51684. */
  51685. Animation.AppendSerializedAnimations = function (source, destination) {
  51686. if (source.animations) {
  51687. destination.animations = [];
  51688. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51689. var animation = source.animations[animationIndex];
  51690. destination.animations.push(animation.serialize());
  51691. }
  51692. }
  51693. };
  51694. /**
  51695. * Use matrix interpolation instead of using direct key value when animating matrices
  51696. */
  51697. Animation.AllowMatricesInterpolation = false;
  51698. /**
  51699. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51700. */
  51701. Animation.AllowMatrixDecomposeForInterpolation = true;
  51702. // Statics
  51703. /**
  51704. * Float animation type
  51705. */
  51706. Animation._ANIMATIONTYPE_FLOAT = 0;
  51707. /**
  51708. * Vector3 animation type
  51709. */
  51710. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51711. /**
  51712. * Quaternion animation type
  51713. */
  51714. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51715. /**
  51716. * Matrix animation type
  51717. */
  51718. Animation._ANIMATIONTYPE_MATRIX = 3;
  51719. /**
  51720. * Color3 animation type
  51721. */
  51722. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51723. /**
  51724. * Vector2 animation type
  51725. */
  51726. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51727. /**
  51728. * Size animation type
  51729. */
  51730. Animation._ANIMATIONTYPE_SIZE = 6;
  51731. /**
  51732. * Relative Loop Mode
  51733. */
  51734. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51735. /**
  51736. * Cycle Loop Mode
  51737. */
  51738. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51739. /**
  51740. * Constant Loop Mode
  51741. */
  51742. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51743. return Animation;
  51744. }());
  51745. BABYLON.Animation = Animation;
  51746. })(BABYLON || (BABYLON = {}));
  51747. //# sourceMappingURL=babylon.animation.js.map
  51748. var BABYLON;
  51749. (function (BABYLON) {
  51750. /**
  51751. * This class defines the direct association between an animation and a target
  51752. */
  51753. var TargetedAnimation = /** @class */ (function () {
  51754. function TargetedAnimation() {
  51755. }
  51756. return TargetedAnimation;
  51757. }());
  51758. BABYLON.TargetedAnimation = TargetedAnimation;
  51759. /**
  51760. * Use this class to create coordinated animations on multiple targets
  51761. */
  51762. var AnimationGroup = /** @class */ (function () {
  51763. function AnimationGroup(name, scene) {
  51764. if (scene === void 0) { scene = null; }
  51765. this.name = name;
  51766. this._targetedAnimations = new Array();
  51767. this._animatables = new Array();
  51768. this._from = Number.MAX_VALUE;
  51769. this._to = -Number.MAX_VALUE;
  51770. this._speedRatio = 1;
  51771. this.onAnimationEndObservable = new BABYLON.Observable();
  51772. /**
  51773. * This observable will notify when all animations have ended.
  51774. */
  51775. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51776. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51777. this._scene.animationGroups.push(this);
  51778. }
  51779. Object.defineProperty(AnimationGroup.prototype, "from", {
  51780. /**
  51781. * Gets the first frame
  51782. */
  51783. get: function () {
  51784. return this._from;
  51785. },
  51786. enumerable: true,
  51787. configurable: true
  51788. });
  51789. Object.defineProperty(AnimationGroup.prototype, "to", {
  51790. /**
  51791. * Gets the last frame
  51792. */
  51793. get: function () {
  51794. return this._to;
  51795. },
  51796. enumerable: true,
  51797. configurable: true
  51798. });
  51799. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51800. /**
  51801. * Define if the animations are started
  51802. */
  51803. get: function () {
  51804. return this._isStarted;
  51805. },
  51806. enumerable: true,
  51807. configurable: true
  51808. });
  51809. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51810. /**
  51811. * Gets or sets the speed ratio to use for all animations
  51812. */
  51813. get: function () {
  51814. return this._speedRatio;
  51815. },
  51816. /**
  51817. * Gets or sets the speed ratio to use for all animations
  51818. */
  51819. set: function (value) {
  51820. if (this._speedRatio === value) {
  51821. return;
  51822. }
  51823. this._speedRatio = value;
  51824. for (var index = 0; index < this._animatables.length; index++) {
  51825. var animatable = this._animatables[index];
  51826. animatable.speedRatio = this._speedRatio;
  51827. }
  51828. },
  51829. enumerable: true,
  51830. configurable: true
  51831. });
  51832. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51833. /**
  51834. * Gets the targeted animations for this animation group
  51835. */
  51836. get: function () {
  51837. return this._targetedAnimations;
  51838. },
  51839. enumerable: true,
  51840. configurable: true
  51841. });
  51842. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51843. /**
  51844. * returning the list of animatables controlled by this animation group.
  51845. */
  51846. get: function () {
  51847. return this._animatables;
  51848. },
  51849. enumerable: true,
  51850. configurable: true
  51851. });
  51852. /**
  51853. * Add an animation (with its target) in the group
  51854. * @param animation defines the animation we want to add
  51855. * @param target defines the target of the animation
  51856. * @returns the {BABYLON.TargetedAnimation} object
  51857. */
  51858. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51859. var targetedAnimation = {
  51860. animation: animation,
  51861. target: target
  51862. };
  51863. var keys = animation.getKeys();
  51864. if (this._from > keys[0].frame) {
  51865. this._from = keys[0].frame;
  51866. }
  51867. if (this._to < keys[keys.length - 1].frame) {
  51868. this._to = keys[keys.length - 1].frame;
  51869. }
  51870. this._targetedAnimations.push(targetedAnimation);
  51871. return targetedAnimation;
  51872. };
  51873. /**
  51874. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51875. * It can add constant keys at begin or end
  51876. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51877. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51878. */
  51879. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51880. if (beginFrame === void 0) { beginFrame = null; }
  51881. if (endFrame === void 0) { endFrame = null; }
  51882. if (beginFrame == null)
  51883. beginFrame = this._from;
  51884. if (endFrame == null)
  51885. endFrame = this._to;
  51886. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51887. var targetedAnimation = this._targetedAnimations[index];
  51888. var keys = targetedAnimation.animation.getKeys();
  51889. var startKey = keys[0];
  51890. var endKey = keys[keys.length - 1];
  51891. if (startKey.frame > beginFrame) {
  51892. var newKey = {
  51893. frame: beginFrame,
  51894. value: startKey.value,
  51895. inTangent: startKey.inTangent,
  51896. outTangent: startKey.outTangent,
  51897. interpolation: startKey.interpolation
  51898. };
  51899. keys.splice(0, 0, newKey);
  51900. }
  51901. if (endKey.frame < endFrame) {
  51902. var newKey = {
  51903. frame: endFrame,
  51904. value: endKey.value,
  51905. inTangent: endKey.outTangent,
  51906. outTangent: endKey.outTangent,
  51907. interpolation: endKey.interpolation
  51908. };
  51909. keys.push(newKey);
  51910. }
  51911. }
  51912. this._from = beginFrame;
  51913. this._to = endFrame;
  51914. return this;
  51915. };
  51916. /**
  51917. * Start all animations on given targets
  51918. * @param loop defines if animations must loop
  51919. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51920. * @param from defines the from key (optional)
  51921. * @param to defines the to key (optional)
  51922. * @returns the current animation group
  51923. */
  51924. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51925. var _this = this;
  51926. if (loop === void 0) { loop = false; }
  51927. if (speedRatio === void 0) { speedRatio = 1; }
  51928. if (this._isStarted || this._targetedAnimations.length === 0) {
  51929. return this;
  51930. }
  51931. var _loop_1 = function (targetedAnimation) {
  51932. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51933. animatable.onAnimationEnd = function () {
  51934. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51935. _this._checkAnimationGroupEnded(animatable);
  51936. };
  51937. this_1._animatables.push(animatable);
  51938. };
  51939. var this_1 = this;
  51940. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51941. var targetedAnimation = _a[_i];
  51942. _loop_1(targetedAnimation);
  51943. }
  51944. this._speedRatio = speedRatio;
  51945. this._isStarted = true;
  51946. return this;
  51947. };
  51948. /**
  51949. * Pause all animations
  51950. */
  51951. AnimationGroup.prototype.pause = function () {
  51952. if (!this._isStarted) {
  51953. return this;
  51954. }
  51955. for (var index = 0; index < this._animatables.length; index++) {
  51956. var animatable = this._animatables[index];
  51957. animatable.pause();
  51958. }
  51959. return this;
  51960. };
  51961. /**
  51962. * Play all animations to initial state
  51963. * This function will start() the animations if they were not started or will restart() them if they were paused
  51964. * @param loop defines if animations must loop
  51965. */
  51966. AnimationGroup.prototype.play = function (loop) {
  51967. // only if all animatables are ready and exist
  51968. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51969. if (loop !== undefined) {
  51970. for (var index = 0; index < this._animatables.length; index++) {
  51971. var animatable = this._animatables[index];
  51972. animatable.loopAnimation = loop;
  51973. }
  51974. }
  51975. this.restart();
  51976. }
  51977. else {
  51978. this.stop();
  51979. this.start(loop, this._speedRatio);
  51980. }
  51981. return this;
  51982. };
  51983. /**
  51984. * Reset all animations to initial state
  51985. */
  51986. AnimationGroup.prototype.reset = function () {
  51987. if (!this._isStarted) {
  51988. return this;
  51989. }
  51990. for (var index = 0; index < this._animatables.length; index++) {
  51991. var animatable = this._animatables[index];
  51992. animatable.reset();
  51993. }
  51994. return this;
  51995. };
  51996. /**
  51997. * Restart animations from key 0
  51998. */
  51999. AnimationGroup.prototype.restart = function () {
  52000. if (!this._isStarted) {
  52001. return this;
  52002. }
  52003. for (var index = 0; index < this._animatables.length; index++) {
  52004. var animatable = this._animatables[index];
  52005. animatable.restart();
  52006. }
  52007. return this;
  52008. };
  52009. /**
  52010. * Stop all animations
  52011. */
  52012. AnimationGroup.prototype.stop = function () {
  52013. if (!this._isStarted) {
  52014. return this;
  52015. }
  52016. for (var index = 0; index < this._animatables.length; index++) {
  52017. var animatable = this._animatables[index];
  52018. animatable.stop();
  52019. }
  52020. this._isStarted = false;
  52021. return this;
  52022. };
  52023. /**
  52024. * Set animation weight for all animatables
  52025. * @param weight defines the weight to use
  52026. * @return the animationGroup
  52027. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52028. */
  52029. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52030. for (var index = 0; index < this._animatables.length; index++) {
  52031. var animatable = this._animatables[index];
  52032. animatable.weight = weight;
  52033. }
  52034. return this;
  52035. };
  52036. /**
  52037. * Synchronize and normalize all animatables with a source animatable
  52038. * @param root defines the root animatable to synchronize with
  52039. * @return the animationGroup
  52040. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52041. */
  52042. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52043. for (var index = 0; index < this._animatables.length; index++) {
  52044. var animatable = this._animatables[index];
  52045. animatable.syncWith(root);
  52046. }
  52047. return this;
  52048. };
  52049. /**
  52050. * Goes to a specific frame in this animation group
  52051. * @param frame the frame number to go to
  52052. * @return the animationGroup
  52053. */
  52054. AnimationGroup.prototype.goToFrame = function (frame) {
  52055. if (!this._isStarted) {
  52056. return this;
  52057. }
  52058. for (var index = 0; index < this._animatables.length; index++) {
  52059. var animatable = this._animatables[index];
  52060. animatable.goToFrame(frame);
  52061. }
  52062. return this;
  52063. };
  52064. /**
  52065. * Dispose all associated resources
  52066. */
  52067. AnimationGroup.prototype.dispose = function () {
  52068. this._targetedAnimations = [];
  52069. this._animatables = [];
  52070. var index = this._scene.animationGroups.indexOf(this);
  52071. if (index > -1) {
  52072. this._scene.animationGroups.splice(index, 1);
  52073. }
  52074. };
  52075. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52076. // animatable should be taken out of the array
  52077. var idx = this._animatables.indexOf(animatable);
  52078. if (idx > -1) {
  52079. this._animatables.splice(idx, 1);
  52080. }
  52081. // all animatables were removed? animation group ended!
  52082. if (this._animatables.length === 0) {
  52083. this._isStarted = false;
  52084. this.onAnimationGroupEndObservable.notifyObservers(this);
  52085. }
  52086. };
  52087. return AnimationGroup;
  52088. }());
  52089. BABYLON.AnimationGroup = AnimationGroup;
  52090. })(BABYLON || (BABYLON = {}));
  52091. //# sourceMappingURL=babylon.animationGroup.js.map
  52092. var BABYLON;
  52093. (function (BABYLON) {
  52094. /**
  52095. * Defines a runtime animation
  52096. */
  52097. var RuntimeAnimation = /** @class */ (function () {
  52098. /**
  52099. * Create a new RuntimeAnimation object
  52100. * @param target defines the target of the animation
  52101. * @param animation defines the source animation object
  52102. * @param scene defines the hosting scene
  52103. * @param host defines the initiating Animatable
  52104. */
  52105. function RuntimeAnimation(target, animation, scene, host) {
  52106. var _this = this;
  52107. this._events = new Array();
  52108. /**
  52109. * The current frame of the runtime animation
  52110. */
  52111. this._currentFrame = 0;
  52112. /**
  52113. * The original value of the runtime animation
  52114. */
  52115. this._originalValue = new Array();
  52116. /**
  52117. * The offsets cache of the runtime animation
  52118. */
  52119. this._offsetsCache = {};
  52120. /**
  52121. * The high limits cache of the runtime animation
  52122. */
  52123. this._highLimitsCache = {};
  52124. /**
  52125. * Specifies if the runtime animation has been stopped
  52126. */
  52127. this._stopped = false;
  52128. /**
  52129. * The blending factor of the runtime animation
  52130. */
  52131. this._blendingFactor = 0;
  52132. /**
  52133. * The target path of the runtime animation
  52134. */
  52135. this._targetPath = "";
  52136. /**
  52137. * The weight of the runtime animation
  52138. */
  52139. this._weight = 1.0;
  52140. /**
  52141. * The ratio offset of the runtime animation
  52142. */
  52143. this._ratioOffset = 0;
  52144. /**
  52145. * The previous delay of the runtime animation
  52146. */
  52147. this._previousDelay = 0;
  52148. /**
  52149. * The previous ratio of the runtime animation
  52150. */
  52151. this._previousRatio = 0;
  52152. this._animation = animation;
  52153. this._target = target;
  52154. this._scene = scene;
  52155. this._host = host;
  52156. animation._runtimeAnimations.push(this);
  52157. // Cloning events locally
  52158. var events = animation.getEvents();
  52159. if (events && events.length > 0) {
  52160. events.forEach(function (e) {
  52161. _this._events.push(e._clone());
  52162. });
  52163. }
  52164. }
  52165. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52166. /**
  52167. * Gets the current frame of the runtime animation
  52168. */
  52169. get: function () {
  52170. return this._currentFrame;
  52171. },
  52172. enumerable: true,
  52173. configurable: true
  52174. });
  52175. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52176. /**
  52177. * Gets the weight of the runtime animation
  52178. */
  52179. get: function () {
  52180. return this._weight;
  52181. },
  52182. enumerable: true,
  52183. configurable: true
  52184. });
  52185. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52186. /**
  52187. * Gets the current value of the runtime animation
  52188. */
  52189. get: function () {
  52190. return this._currentValue;
  52191. },
  52192. enumerable: true,
  52193. configurable: true
  52194. });
  52195. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52196. /**
  52197. * Gets the target path of the runtime animation
  52198. */
  52199. get: function () {
  52200. return this._targetPath;
  52201. },
  52202. enumerable: true,
  52203. configurable: true
  52204. });
  52205. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52206. /**
  52207. * Gets the actual target of the runtime animation
  52208. */
  52209. get: function () {
  52210. return this._activeTarget;
  52211. },
  52212. enumerable: true,
  52213. configurable: true
  52214. });
  52215. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52216. /**
  52217. * Gets the animation from the runtime animation
  52218. */
  52219. get: function () {
  52220. return this._animation;
  52221. },
  52222. enumerable: true,
  52223. configurable: true
  52224. });
  52225. /**
  52226. * Resets the runtime animation to the beginning
  52227. * @param restoreOriginal defines whether to restore the target property to the original value
  52228. */
  52229. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52230. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52231. if (restoreOriginal) {
  52232. if (this._target instanceof Array) {
  52233. var index = 0;
  52234. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52235. var target = _a[_i];
  52236. if (this._originalValue[index] !== undefined) {
  52237. this._setValue(target, this._originalValue[index], -1);
  52238. }
  52239. index++;
  52240. }
  52241. }
  52242. else {
  52243. if (this._originalValue[0] !== undefined) {
  52244. this._setValue(this._target, this._originalValue[0], -1);
  52245. }
  52246. }
  52247. }
  52248. this._offsetsCache = {};
  52249. this._highLimitsCache = {};
  52250. this._currentFrame = 0;
  52251. this._blendingFactor = 0;
  52252. this._originalValue = new Array();
  52253. // Events
  52254. for (var index = 0; index < this._events.length; index++) {
  52255. this._events[index].isDone = false;
  52256. }
  52257. };
  52258. /**
  52259. * Specifies if the runtime animation is stopped
  52260. * @returns Boolean specifying if the runtime animation is stopped
  52261. */
  52262. RuntimeAnimation.prototype.isStopped = function () {
  52263. return this._stopped;
  52264. };
  52265. /**
  52266. * Disposes of the runtime animation
  52267. */
  52268. RuntimeAnimation.prototype.dispose = function () {
  52269. var index = this._animation.runtimeAnimations.indexOf(this);
  52270. if (index > -1) {
  52271. this._animation.runtimeAnimations.splice(index, 1);
  52272. }
  52273. };
  52274. /**
  52275. * Interpolates the animation from the current frame
  52276. * @param currentFrame The frame to interpolate the animation to
  52277. * @param repeatCount The number of times that the animation should loop
  52278. * @param loopMode The type of looping mode to use
  52279. * @param offsetValue Animation offset value
  52280. * @param highLimitValue The high limit value
  52281. * @returns The interpolated value
  52282. */
  52283. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52284. this._currentFrame = currentFrame;
  52285. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52286. this._workValue = BABYLON.Matrix.Zero();
  52287. }
  52288. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52289. };
  52290. /**
  52291. * Apply the interpolated value to the target
  52292. * @param currentValue defines the value computed by the animation
  52293. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52294. */
  52295. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52296. if (weight === void 0) { weight = 1.0; }
  52297. if (this._target instanceof Array) {
  52298. var index = 0;
  52299. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52300. var target = _a[_i];
  52301. this._setValue(target, currentValue, weight, index);
  52302. index++;
  52303. }
  52304. }
  52305. else {
  52306. this._setValue(this._target, currentValue, weight);
  52307. }
  52308. };
  52309. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52310. if (targetIndex === void 0) { targetIndex = 0; }
  52311. // Set value
  52312. var path;
  52313. var destination;
  52314. var targetPropertyPath = this._animation.targetPropertyPath;
  52315. if (targetPropertyPath.length > 1) {
  52316. var property = target[targetPropertyPath[0]];
  52317. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52318. property = property[targetPropertyPath[index]];
  52319. }
  52320. path = targetPropertyPath[targetPropertyPath.length - 1];
  52321. destination = property;
  52322. }
  52323. else {
  52324. path = targetPropertyPath[0];
  52325. destination = target;
  52326. }
  52327. this._targetPath = path;
  52328. this._activeTarget = destination;
  52329. this._weight = weight;
  52330. if (this._originalValue[targetIndex] === undefined) {
  52331. var originalValue = void 0;
  52332. if (destination.getRestPose && path === "_matrix") { // For bones
  52333. originalValue = destination.getRestPose();
  52334. }
  52335. else {
  52336. originalValue = destination[path];
  52337. }
  52338. if (originalValue && originalValue.clone) {
  52339. this._originalValue[targetIndex] = originalValue.clone();
  52340. }
  52341. else {
  52342. this._originalValue[targetIndex] = originalValue;
  52343. }
  52344. }
  52345. // Blending
  52346. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52347. if (enableBlending && this._blendingFactor <= 1.0) {
  52348. if (!this._originalBlendValue) {
  52349. var originalValue = destination[path];
  52350. if (originalValue.clone) {
  52351. this._originalBlendValue = originalValue.clone();
  52352. }
  52353. else {
  52354. this._originalBlendValue = originalValue;
  52355. }
  52356. }
  52357. if (this._originalBlendValue.m) { // Matrix
  52358. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52359. if (this._currentValue) {
  52360. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52361. }
  52362. else {
  52363. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52364. }
  52365. }
  52366. else {
  52367. if (this._currentValue) {
  52368. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52369. }
  52370. else {
  52371. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52372. }
  52373. }
  52374. }
  52375. else {
  52376. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52377. }
  52378. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52379. this._blendingFactor += blendingSpeed;
  52380. }
  52381. else {
  52382. this._currentValue = currentValue;
  52383. }
  52384. if (weight !== -1.0) {
  52385. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52386. }
  52387. else {
  52388. destination[path] = this._currentValue;
  52389. }
  52390. if (target.markAsDirty) {
  52391. target.markAsDirty(this._animation.targetProperty);
  52392. }
  52393. };
  52394. /**
  52395. * Gets the loop pmode of the runtime animation
  52396. * @returns Loop Mode
  52397. */
  52398. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52399. if (this._target && this._target.animationPropertiesOverride) {
  52400. return this._target.animationPropertiesOverride.loopMode;
  52401. }
  52402. return this._animation.loopMode;
  52403. };
  52404. /**
  52405. * Move the current animation to a given frame
  52406. * @param frame defines the frame to move to
  52407. */
  52408. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52409. var keys = this._animation.getKeys();
  52410. if (frame < keys[0].frame) {
  52411. frame = keys[0].frame;
  52412. }
  52413. else if (frame > keys[keys.length - 1].frame) {
  52414. frame = keys[keys.length - 1].frame;
  52415. }
  52416. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52417. this.setValue(currentValue, -1);
  52418. };
  52419. /**
  52420. * @hidden Internal use only
  52421. */
  52422. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52423. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52424. this._ratioOffset = this._previousRatio - newRatio;
  52425. };
  52426. /**
  52427. * Execute the current animation
  52428. * @param delay defines the delay to add to the current frame
  52429. * @param from defines the lower bound of the animation range
  52430. * @param to defines the upper bound of the animation range
  52431. * @param loop defines if the current animation must loop
  52432. * @param speedRatio defines the current speed ratio
  52433. * @param weight defines the weight of the animation (default is -1 so no weight)
  52434. * @returns a boolean indicating if the animation has ended
  52435. */
  52436. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52437. if (weight === void 0) { weight = -1.0; }
  52438. var targetPropertyPath = this._animation.targetPropertyPath;
  52439. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52440. this._stopped = true;
  52441. return false;
  52442. }
  52443. var returnValue = true;
  52444. var keys = this._animation.getKeys();
  52445. // Adding a start key at frame 0 if missing
  52446. if (keys[0].frame !== 0) {
  52447. var newKey = { frame: 0, value: keys[0].value };
  52448. keys.splice(0, 0, newKey);
  52449. }
  52450. // Check limits
  52451. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52452. from = keys[0].frame;
  52453. }
  52454. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52455. to = keys[keys.length - 1].frame;
  52456. }
  52457. //to and from cannot be the same key
  52458. if (from === to) {
  52459. if (from > keys[0].frame) {
  52460. from--;
  52461. }
  52462. else if (to < keys[keys.length - 1].frame) {
  52463. to++;
  52464. }
  52465. }
  52466. // Compute ratio
  52467. var range = to - from;
  52468. var offsetValue;
  52469. // ratio represents the frame delta between from and to
  52470. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52471. var highLimitValue = 0;
  52472. this._previousDelay = delay;
  52473. this._previousRatio = ratio;
  52474. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52475. returnValue = false;
  52476. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52477. }
  52478. else {
  52479. // Get max value if required
  52480. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52481. var keyOffset = to.toString() + from.toString();
  52482. if (!this._offsetsCache[keyOffset]) {
  52483. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52484. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52485. switch (this._animation.dataType) {
  52486. // Float
  52487. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52488. this._offsetsCache[keyOffset] = toValue - fromValue;
  52489. break;
  52490. // Quaternion
  52491. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52492. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52493. break;
  52494. // Vector3
  52495. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52496. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52497. // Vector2
  52498. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52499. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52500. // Size
  52501. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52502. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52503. // Color3
  52504. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52505. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52506. default:
  52507. break;
  52508. }
  52509. this._highLimitsCache[keyOffset] = toValue;
  52510. }
  52511. highLimitValue = this._highLimitsCache[keyOffset];
  52512. offsetValue = this._offsetsCache[keyOffset];
  52513. }
  52514. }
  52515. if (offsetValue === undefined) {
  52516. switch (this._animation.dataType) {
  52517. // Float
  52518. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52519. offsetValue = 0;
  52520. break;
  52521. // Quaternion
  52522. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52523. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52524. break;
  52525. // Vector3
  52526. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52527. offsetValue = BABYLON.Vector3.Zero();
  52528. break;
  52529. // Vector2
  52530. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52531. offsetValue = BABYLON.Vector2.Zero();
  52532. break;
  52533. // Size
  52534. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52535. offsetValue = BABYLON.Size.Zero();
  52536. break;
  52537. // Color3
  52538. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52539. offsetValue = BABYLON.Color3.Black();
  52540. }
  52541. }
  52542. // Compute value
  52543. var repeatCount = (ratio / range) >> 0;
  52544. var currentFrame = returnValue ? from + ratio % range : to;
  52545. // Need to normalize?
  52546. if (this._host && this._host.syncRoot) {
  52547. var syncRoot = this._host.syncRoot;
  52548. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52549. currentFrame = from + (to - from) * hostNormalizedFrame;
  52550. }
  52551. // Reset events if looping
  52552. var events = this._events;
  52553. if (range > 0 && this.currentFrame > currentFrame ||
  52554. range < 0 && this.currentFrame < currentFrame) {
  52555. // Need to reset animation events
  52556. for (var index = 0; index < events.length; index++) {
  52557. if (!events[index].onlyOnce) {
  52558. // reset event, the animation is looping
  52559. events[index].isDone = false;
  52560. }
  52561. }
  52562. }
  52563. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52564. // Set value
  52565. this.setValue(currentValue, weight);
  52566. // Check events
  52567. for (var index = 0; index < events.length; index++) {
  52568. // Make sure current frame has passed event frame and that event frame is within the current range
  52569. // Also, handle both forward and reverse animations
  52570. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52571. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52572. var event = events[index];
  52573. if (!event.isDone) {
  52574. // If event should be done only once, remove it.
  52575. if (event.onlyOnce) {
  52576. events.splice(index, 1);
  52577. index--;
  52578. }
  52579. event.isDone = true;
  52580. event.action();
  52581. } // Don't do anything if the event has already be done.
  52582. }
  52583. }
  52584. if (!returnValue) {
  52585. this._stopped = true;
  52586. }
  52587. return returnValue;
  52588. };
  52589. return RuntimeAnimation;
  52590. }());
  52591. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52592. })(BABYLON || (BABYLON = {}));
  52593. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52594. var BABYLON;
  52595. (function (BABYLON) {
  52596. var Animatable = /** @class */ (function () {
  52597. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52598. if (fromFrame === void 0) { fromFrame = 0; }
  52599. if (toFrame === void 0) { toFrame = 100; }
  52600. if (loopAnimation === void 0) { loopAnimation = false; }
  52601. if (speedRatio === void 0) { speedRatio = 1.0; }
  52602. this.target = target;
  52603. this.fromFrame = fromFrame;
  52604. this.toFrame = toFrame;
  52605. this.loopAnimation = loopAnimation;
  52606. this.onAnimationEnd = onAnimationEnd;
  52607. this._localDelayOffset = null;
  52608. this._pausedDelay = null;
  52609. this._runtimeAnimations = new Array();
  52610. this._paused = false;
  52611. this._speedRatio = 1;
  52612. this._weight = -1.0;
  52613. this.animationStarted = false;
  52614. /**
  52615. * Observer raised when the animation ends
  52616. */
  52617. this.onAnimationEndObservable = new BABYLON.Observable();
  52618. this._scene = scene;
  52619. if (animations) {
  52620. this.appendAnimations(target, animations);
  52621. }
  52622. this._speedRatio = speedRatio;
  52623. scene._activeAnimatables.push(this);
  52624. }
  52625. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52626. /**
  52627. * Gets the root Animatable used to synchronize and normalize animations
  52628. */
  52629. get: function () {
  52630. return this._syncRoot;
  52631. },
  52632. enumerable: true,
  52633. configurable: true
  52634. });
  52635. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52636. /**
  52637. * Gets the current frame of the first RuntimeAnimation
  52638. * Used to synchronize Animatables
  52639. */
  52640. get: function () {
  52641. if (this._runtimeAnimations.length === 0) {
  52642. return 0;
  52643. }
  52644. return this._runtimeAnimations[0].currentFrame;
  52645. },
  52646. enumerable: true,
  52647. configurable: true
  52648. });
  52649. Object.defineProperty(Animatable.prototype, "weight", {
  52650. /**
  52651. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52652. */
  52653. get: function () {
  52654. return this._weight;
  52655. },
  52656. set: function (value) {
  52657. if (value === -1) { // -1 is ok and means no weight
  52658. this._weight = -1;
  52659. return;
  52660. }
  52661. // Else weight must be in [0, 1] range
  52662. this._weight = Math.min(Math.max(value, 0), 1.0);
  52663. },
  52664. enumerable: true,
  52665. configurable: true
  52666. });
  52667. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52668. /**
  52669. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52670. */
  52671. get: function () {
  52672. return this._speedRatio;
  52673. },
  52674. set: function (value) {
  52675. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52676. var animation = this._runtimeAnimations[index];
  52677. animation._prepareForSpeedRatioChange(value);
  52678. }
  52679. this._speedRatio = value;
  52680. },
  52681. enumerable: true,
  52682. configurable: true
  52683. });
  52684. // Methods
  52685. /**
  52686. * Synchronize and normalize current Animatable with a source Animatable
  52687. * This is useful when using animation weights and when animations are not of the same length
  52688. * @param root defines the root Animatable to synchronize with
  52689. * @returns the current Animatable
  52690. */
  52691. Animatable.prototype.syncWith = function (root) {
  52692. this._syncRoot = root;
  52693. if (root) {
  52694. // Make sure this animatable will animate after the root
  52695. var index = this._scene._activeAnimatables.indexOf(this);
  52696. if (index > -1) {
  52697. this._scene._activeAnimatables.splice(index, 1);
  52698. this._scene._activeAnimatables.push(this);
  52699. }
  52700. }
  52701. return this;
  52702. };
  52703. Animatable.prototype.getAnimations = function () {
  52704. return this._runtimeAnimations;
  52705. };
  52706. Animatable.prototype.appendAnimations = function (target, animations) {
  52707. for (var index = 0; index < animations.length; index++) {
  52708. var animation = animations[index];
  52709. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52710. }
  52711. };
  52712. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52713. var runtimeAnimations = this._runtimeAnimations;
  52714. for (var index = 0; index < runtimeAnimations.length; index++) {
  52715. if (runtimeAnimations[index].animation.targetProperty === property) {
  52716. return runtimeAnimations[index].animation;
  52717. }
  52718. }
  52719. return null;
  52720. };
  52721. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52722. var runtimeAnimations = this._runtimeAnimations;
  52723. for (var index = 0; index < runtimeAnimations.length; index++) {
  52724. if (runtimeAnimations[index].animation.targetProperty === property) {
  52725. return runtimeAnimations[index];
  52726. }
  52727. }
  52728. return null;
  52729. };
  52730. Animatable.prototype.reset = function () {
  52731. var runtimeAnimations = this._runtimeAnimations;
  52732. for (var index = 0; index < runtimeAnimations.length; index++) {
  52733. runtimeAnimations[index].reset(true);
  52734. }
  52735. this._localDelayOffset = null;
  52736. this._pausedDelay = null;
  52737. };
  52738. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52739. var runtimeAnimations = this._runtimeAnimations;
  52740. for (var index = 0; index < runtimeAnimations.length; index++) {
  52741. runtimeAnimations[index].animation.enableBlending = true;
  52742. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52743. }
  52744. };
  52745. Animatable.prototype.disableBlending = function () {
  52746. var runtimeAnimations = this._runtimeAnimations;
  52747. for (var index = 0; index < runtimeAnimations.length; index++) {
  52748. runtimeAnimations[index].animation.enableBlending = false;
  52749. }
  52750. };
  52751. Animatable.prototype.goToFrame = function (frame) {
  52752. var runtimeAnimations = this._runtimeAnimations;
  52753. if (runtimeAnimations[0]) {
  52754. var fps = runtimeAnimations[0].animation.framePerSecond;
  52755. var currentFrame = runtimeAnimations[0].currentFrame;
  52756. var adjustTime = frame - currentFrame;
  52757. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52758. if (this._localDelayOffset === null) {
  52759. this._localDelayOffset = 0;
  52760. }
  52761. this._localDelayOffset -= delay;
  52762. }
  52763. for (var index = 0; index < runtimeAnimations.length; index++) {
  52764. runtimeAnimations[index].goToFrame(frame);
  52765. }
  52766. };
  52767. Animatable.prototype.pause = function () {
  52768. if (this._paused) {
  52769. return;
  52770. }
  52771. this._paused = true;
  52772. };
  52773. Animatable.prototype.restart = function () {
  52774. this._paused = false;
  52775. };
  52776. Animatable.prototype._raiseOnAnimationEnd = function () {
  52777. if (this.onAnimationEnd) {
  52778. this.onAnimationEnd();
  52779. }
  52780. this.onAnimationEndObservable.notifyObservers(this);
  52781. };
  52782. Animatable.prototype.stop = function (animationName) {
  52783. if (animationName) {
  52784. var idx = this._scene._activeAnimatables.indexOf(this);
  52785. if (idx > -1) {
  52786. var runtimeAnimations = this._runtimeAnimations;
  52787. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52788. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52789. continue;
  52790. }
  52791. runtimeAnimations[index].dispose();
  52792. runtimeAnimations.splice(index, 1);
  52793. }
  52794. if (runtimeAnimations.length == 0) {
  52795. this._scene._activeAnimatables.splice(idx, 1);
  52796. this._raiseOnAnimationEnd();
  52797. }
  52798. }
  52799. }
  52800. else {
  52801. var index = this._scene._activeAnimatables.indexOf(this);
  52802. if (index > -1) {
  52803. this._scene._activeAnimatables.splice(index, 1);
  52804. var runtimeAnimations = this._runtimeAnimations;
  52805. for (var index = 0; index < runtimeAnimations.length; index++) {
  52806. runtimeAnimations[index].dispose();
  52807. }
  52808. this._raiseOnAnimationEnd();
  52809. }
  52810. }
  52811. };
  52812. /**
  52813. * Wait asynchronously for the animation to end
  52814. * @returns a promise which will be fullfilled when the animation ends
  52815. */
  52816. Animatable.prototype.waitAsync = function () {
  52817. var _this = this;
  52818. return new Promise(function (resolve, reject) {
  52819. _this.onAnimationEndObservable.add(function () {
  52820. resolve(_this);
  52821. }, undefined, undefined, _this, true);
  52822. });
  52823. };
  52824. /** @hidden */
  52825. Animatable.prototype._animate = function (delay) {
  52826. if (this._paused) {
  52827. this.animationStarted = false;
  52828. if (this._pausedDelay === null) {
  52829. this._pausedDelay = delay;
  52830. }
  52831. return true;
  52832. }
  52833. if (this._localDelayOffset === null) {
  52834. this._localDelayOffset = delay;
  52835. this._pausedDelay = null;
  52836. }
  52837. else if (this._pausedDelay !== null) {
  52838. this._localDelayOffset += delay - this._pausedDelay;
  52839. this._pausedDelay = null;
  52840. }
  52841. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52842. return true;
  52843. }
  52844. // Animating
  52845. var running = false;
  52846. var runtimeAnimations = this._runtimeAnimations;
  52847. var index;
  52848. for (index = 0; index < runtimeAnimations.length; index++) {
  52849. var animation = runtimeAnimations[index];
  52850. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52851. running = running || isRunning;
  52852. }
  52853. this.animationStarted = running;
  52854. if (!running) {
  52855. // Remove from active animatables
  52856. index = this._scene._activeAnimatables.indexOf(this);
  52857. this._scene._activeAnimatables.splice(index, 1);
  52858. // Dispose all runtime animations
  52859. for (index = 0; index < runtimeAnimations.length; index++) {
  52860. runtimeAnimations[index].dispose();
  52861. }
  52862. this._raiseOnAnimationEnd();
  52863. this.onAnimationEnd = null;
  52864. this.onAnimationEndObservable.clear();
  52865. }
  52866. return running;
  52867. };
  52868. return Animatable;
  52869. }());
  52870. BABYLON.Animatable = Animatable;
  52871. })(BABYLON || (BABYLON = {}));
  52872. //# sourceMappingURL=babylon.animatable.js.map
  52873. var BABYLON;
  52874. (function (BABYLON) {
  52875. var EasingFunction = /** @class */ (function () {
  52876. function EasingFunction() {
  52877. // Properties
  52878. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52879. }
  52880. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52881. get: function () {
  52882. return EasingFunction._EASINGMODE_EASEIN;
  52883. },
  52884. enumerable: true,
  52885. configurable: true
  52886. });
  52887. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52888. get: function () {
  52889. return EasingFunction._EASINGMODE_EASEOUT;
  52890. },
  52891. enumerable: true,
  52892. configurable: true
  52893. });
  52894. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52895. get: function () {
  52896. return EasingFunction._EASINGMODE_EASEINOUT;
  52897. },
  52898. enumerable: true,
  52899. configurable: true
  52900. });
  52901. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52902. var n = Math.min(Math.max(easingMode, 0), 2);
  52903. this._easingMode = n;
  52904. };
  52905. EasingFunction.prototype.getEasingMode = function () {
  52906. return this._easingMode;
  52907. };
  52908. EasingFunction.prototype.easeInCore = function (gradient) {
  52909. throw new Error('You must implement this method');
  52910. };
  52911. EasingFunction.prototype.ease = function (gradient) {
  52912. switch (this._easingMode) {
  52913. case EasingFunction.EASINGMODE_EASEIN:
  52914. return this.easeInCore(gradient);
  52915. case EasingFunction.EASINGMODE_EASEOUT:
  52916. return (1 - this.easeInCore(1 - gradient));
  52917. }
  52918. if (gradient >= 0.5) {
  52919. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52920. }
  52921. return (this.easeInCore(gradient * 2) * 0.5);
  52922. };
  52923. //Statics
  52924. EasingFunction._EASINGMODE_EASEIN = 0;
  52925. EasingFunction._EASINGMODE_EASEOUT = 1;
  52926. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52927. return EasingFunction;
  52928. }());
  52929. BABYLON.EasingFunction = EasingFunction;
  52930. var CircleEase = /** @class */ (function (_super) {
  52931. __extends(CircleEase, _super);
  52932. function CircleEase() {
  52933. return _super !== null && _super.apply(this, arguments) || this;
  52934. }
  52935. CircleEase.prototype.easeInCore = function (gradient) {
  52936. gradient = Math.max(0, Math.min(1, gradient));
  52937. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52938. };
  52939. return CircleEase;
  52940. }(EasingFunction));
  52941. BABYLON.CircleEase = CircleEase;
  52942. var BackEase = /** @class */ (function (_super) {
  52943. __extends(BackEase, _super);
  52944. function BackEase(amplitude) {
  52945. if (amplitude === void 0) { amplitude = 1; }
  52946. var _this = _super.call(this) || this;
  52947. _this.amplitude = amplitude;
  52948. return _this;
  52949. }
  52950. BackEase.prototype.easeInCore = function (gradient) {
  52951. var num = Math.max(0, this.amplitude);
  52952. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52953. };
  52954. return BackEase;
  52955. }(EasingFunction));
  52956. BABYLON.BackEase = BackEase;
  52957. var BounceEase = /** @class */ (function (_super) {
  52958. __extends(BounceEase, _super);
  52959. function BounceEase(bounces, bounciness) {
  52960. if (bounces === void 0) { bounces = 3; }
  52961. if (bounciness === void 0) { bounciness = 2; }
  52962. var _this = _super.call(this) || this;
  52963. _this.bounces = bounces;
  52964. _this.bounciness = bounciness;
  52965. return _this;
  52966. }
  52967. BounceEase.prototype.easeInCore = function (gradient) {
  52968. var y = Math.max(0.0, this.bounces);
  52969. var bounciness = this.bounciness;
  52970. if (bounciness <= 1.0) {
  52971. bounciness = 1.001;
  52972. }
  52973. var num9 = Math.pow(bounciness, y);
  52974. var num5 = 1.0 - bounciness;
  52975. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52976. var num15 = gradient * num4;
  52977. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52978. var num3 = Math.floor(num65);
  52979. var num13 = num3 + 1.0;
  52980. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52981. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52982. var num7 = (num8 + num12) * 0.5;
  52983. var num6 = gradient - num7;
  52984. var num2 = num7 - num8;
  52985. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52986. };
  52987. return BounceEase;
  52988. }(EasingFunction));
  52989. BABYLON.BounceEase = BounceEase;
  52990. var CubicEase = /** @class */ (function (_super) {
  52991. __extends(CubicEase, _super);
  52992. function CubicEase() {
  52993. return _super !== null && _super.apply(this, arguments) || this;
  52994. }
  52995. CubicEase.prototype.easeInCore = function (gradient) {
  52996. return (gradient * gradient * gradient);
  52997. };
  52998. return CubicEase;
  52999. }(EasingFunction));
  53000. BABYLON.CubicEase = CubicEase;
  53001. var ElasticEase = /** @class */ (function (_super) {
  53002. __extends(ElasticEase, _super);
  53003. function ElasticEase(oscillations, springiness) {
  53004. if (oscillations === void 0) { oscillations = 3; }
  53005. if (springiness === void 0) { springiness = 3; }
  53006. var _this = _super.call(this) || this;
  53007. _this.oscillations = oscillations;
  53008. _this.springiness = springiness;
  53009. return _this;
  53010. }
  53011. ElasticEase.prototype.easeInCore = function (gradient) {
  53012. var num2;
  53013. var num3 = Math.max(0.0, this.oscillations);
  53014. var num = Math.max(0.0, this.springiness);
  53015. if (num == 0) {
  53016. num2 = gradient;
  53017. }
  53018. else {
  53019. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53020. }
  53021. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53022. };
  53023. return ElasticEase;
  53024. }(EasingFunction));
  53025. BABYLON.ElasticEase = ElasticEase;
  53026. var ExponentialEase = /** @class */ (function (_super) {
  53027. __extends(ExponentialEase, _super);
  53028. function ExponentialEase(exponent) {
  53029. if (exponent === void 0) { exponent = 2; }
  53030. var _this = _super.call(this) || this;
  53031. _this.exponent = exponent;
  53032. return _this;
  53033. }
  53034. ExponentialEase.prototype.easeInCore = function (gradient) {
  53035. if (this.exponent <= 0) {
  53036. return gradient;
  53037. }
  53038. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53039. };
  53040. return ExponentialEase;
  53041. }(EasingFunction));
  53042. BABYLON.ExponentialEase = ExponentialEase;
  53043. var PowerEase = /** @class */ (function (_super) {
  53044. __extends(PowerEase, _super);
  53045. function PowerEase(power) {
  53046. if (power === void 0) { power = 2; }
  53047. var _this = _super.call(this) || this;
  53048. _this.power = power;
  53049. return _this;
  53050. }
  53051. PowerEase.prototype.easeInCore = function (gradient) {
  53052. var y = Math.max(0.0, this.power);
  53053. return Math.pow(gradient, y);
  53054. };
  53055. return PowerEase;
  53056. }(EasingFunction));
  53057. BABYLON.PowerEase = PowerEase;
  53058. var QuadraticEase = /** @class */ (function (_super) {
  53059. __extends(QuadraticEase, _super);
  53060. function QuadraticEase() {
  53061. return _super !== null && _super.apply(this, arguments) || this;
  53062. }
  53063. QuadraticEase.prototype.easeInCore = function (gradient) {
  53064. return (gradient * gradient);
  53065. };
  53066. return QuadraticEase;
  53067. }(EasingFunction));
  53068. BABYLON.QuadraticEase = QuadraticEase;
  53069. var QuarticEase = /** @class */ (function (_super) {
  53070. __extends(QuarticEase, _super);
  53071. function QuarticEase() {
  53072. return _super !== null && _super.apply(this, arguments) || this;
  53073. }
  53074. QuarticEase.prototype.easeInCore = function (gradient) {
  53075. return (gradient * gradient * gradient * gradient);
  53076. };
  53077. return QuarticEase;
  53078. }(EasingFunction));
  53079. BABYLON.QuarticEase = QuarticEase;
  53080. var QuinticEase = /** @class */ (function (_super) {
  53081. __extends(QuinticEase, _super);
  53082. function QuinticEase() {
  53083. return _super !== null && _super.apply(this, arguments) || this;
  53084. }
  53085. QuinticEase.prototype.easeInCore = function (gradient) {
  53086. return (gradient * gradient * gradient * gradient * gradient);
  53087. };
  53088. return QuinticEase;
  53089. }(EasingFunction));
  53090. BABYLON.QuinticEase = QuinticEase;
  53091. var SineEase = /** @class */ (function (_super) {
  53092. __extends(SineEase, _super);
  53093. function SineEase() {
  53094. return _super !== null && _super.apply(this, arguments) || this;
  53095. }
  53096. SineEase.prototype.easeInCore = function (gradient) {
  53097. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53098. };
  53099. return SineEase;
  53100. }(EasingFunction));
  53101. BABYLON.SineEase = SineEase;
  53102. var BezierCurveEase = /** @class */ (function (_super) {
  53103. __extends(BezierCurveEase, _super);
  53104. function BezierCurveEase(x1, y1, x2, y2) {
  53105. if (x1 === void 0) { x1 = 0; }
  53106. if (y1 === void 0) { y1 = 0; }
  53107. if (x2 === void 0) { x2 = 1; }
  53108. if (y2 === void 0) { y2 = 1; }
  53109. var _this = _super.call(this) || this;
  53110. _this.x1 = x1;
  53111. _this.y1 = y1;
  53112. _this.x2 = x2;
  53113. _this.y2 = y2;
  53114. return _this;
  53115. }
  53116. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53117. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53118. };
  53119. return BezierCurveEase;
  53120. }(EasingFunction));
  53121. BABYLON.BezierCurveEase = BezierCurveEase;
  53122. })(BABYLON || (BABYLON = {}));
  53123. //# sourceMappingURL=babylon.easing.js.map
  53124. var BABYLON;
  53125. (function (BABYLON) {
  53126. /**
  53127. * A Condition applied to an Action
  53128. */
  53129. var Condition = /** @class */ (function () {
  53130. /**
  53131. * Creates a new Condition
  53132. * @param actionManager the manager of the action the condition is applied to
  53133. */
  53134. function Condition(actionManager) {
  53135. this._actionManager = actionManager;
  53136. }
  53137. /**
  53138. * Check if the current condition is valid
  53139. * @returns a boolean
  53140. */
  53141. Condition.prototype.isValid = function () {
  53142. return true;
  53143. };
  53144. /**
  53145. * Internal only
  53146. * @hidden
  53147. */
  53148. Condition.prototype._getProperty = function (propertyPath) {
  53149. return this._actionManager._getProperty(propertyPath);
  53150. };
  53151. /**
  53152. * Internal only
  53153. * @hidden
  53154. */
  53155. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53156. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53157. };
  53158. /**
  53159. * Serialize placeholder for child classes
  53160. * @returns the serialized object
  53161. */
  53162. Condition.prototype.serialize = function () {
  53163. };
  53164. /**
  53165. * Internal only
  53166. * @hidden
  53167. */
  53168. Condition.prototype._serialize = function (serializedCondition) {
  53169. return {
  53170. type: 2,
  53171. children: [],
  53172. name: serializedCondition.name,
  53173. properties: serializedCondition.properties
  53174. };
  53175. };
  53176. return Condition;
  53177. }());
  53178. BABYLON.Condition = Condition;
  53179. /**
  53180. * Defines specific conditional operators as extensions of Condition
  53181. */
  53182. var ValueCondition = /** @class */ (function (_super) {
  53183. __extends(ValueCondition, _super);
  53184. /**
  53185. * Creates a new ValueCondition
  53186. * @param actionManager manager for the action the condition applies to
  53187. * @param target for the action
  53188. * @param propertyPath path to specify the property of the target the conditional operator uses
  53189. * @param value the value compared by the conditional operator against the current value of the property
  53190. * @param operator the conditional operator, default ValueCondition.IsEqual
  53191. */
  53192. function ValueCondition(actionManager, target,
  53193. /** path to specify the property of the target the conditional operator uses */
  53194. propertyPath,
  53195. /** the value compared by the conditional operator against the current value of the property */
  53196. value,
  53197. /** the conditional operator, default ValueCondition.IsEqual */
  53198. operator) {
  53199. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53200. var _this = _super.call(this, actionManager) || this;
  53201. _this.propertyPath = propertyPath;
  53202. _this.value = value;
  53203. _this.operator = operator;
  53204. _this._target = target;
  53205. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53206. _this._property = _this._getProperty(_this.propertyPath);
  53207. return _this;
  53208. }
  53209. Object.defineProperty(ValueCondition, "IsEqual", {
  53210. /**
  53211. * returns the number for IsEqual
  53212. */
  53213. get: function () {
  53214. return ValueCondition._IsEqual;
  53215. },
  53216. enumerable: true,
  53217. configurable: true
  53218. });
  53219. Object.defineProperty(ValueCondition, "IsDifferent", {
  53220. /**
  53221. * Returns the number for IsDifferent
  53222. */
  53223. get: function () {
  53224. return ValueCondition._IsDifferent;
  53225. },
  53226. enumerable: true,
  53227. configurable: true
  53228. });
  53229. Object.defineProperty(ValueCondition, "IsGreater", {
  53230. /**
  53231. * Returns the number for IsGreater
  53232. */
  53233. get: function () {
  53234. return ValueCondition._IsGreater;
  53235. },
  53236. enumerable: true,
  53237. configurable: true
  53238. });
  53239. Object.defineProperty(ValueCondition, "IsLesser", {
  53240. /**
  53241. * Returns the number for IsLesser
  53242. */
  53243. get: function () {
  53244. return ValueCondition._IsLesser;
  53245. },
  53246. enumerable: true,
  53247. configurable: true
  53248. });
  53249. /**
  53250. * Compares the given value with the property value for the specified conditional operator
  53251. * @returns the result of the comparison
  53252. */
  53253. ValueCondition.prototype.isValid = function () {
  53254. switch (this.operator) {
  53255. case ValueCondition.IsGreater:
  53256. return this._effectiveTarget[this._property] > this.value;
  53257. case ValueCondition.IsLesser:
  53258. return this._effectiveTarget[this._property] < this.value;
  53259. case ValueCondition.IsEqual:
  53260. case ValueCondition.IsDifferent:
  53261. var check;
  53262. if (this.value.equals) {
  53263. check = this.value.equals(this._effectiveTarget[this._property]);
  53264. }
  53265. else {
  53266. check = this.value === this._effectiveTarget[this._property];
  53267. }
  53268. return this.operator === ValueCondition.IsEqual ? check : !check;
  53269. }
  53270. return false;
  53271. };
  53272. /**
  53273. * Serialize the ValueCondition into a JSON compatible object
  53274. * @returns serialization object
  53275. */
  53276. ValueCondition.prototype.serialize = function () {
  53277. return this._serialize({
  53278. name: "ValueCondition",
  53279. properties: [
  53280. BABYLON.Action._GetTargetProperty(this._target),
  53281. { name: "propertyPath", value: this.propertyPath },
  53282. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53283. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53284. ]
  53285. });
  53286. };
  53287. /**
  53288. * Gets the name of the conditional operator for the ValueCondition
  53289. * @param operator the conditional operator
  53290. * @returns the name
  53291. */
  53292. ValueCondition.GetOperatorName = function (operator) {
  53293. switch (operator) {
  53294. case ValueCondition._IsEqual: return "IsEqual";
  53295. case ValueCondition._IsDifferent: return "IsDifferent";
  53296. case ValueCondition._IsGreater: return "IsGreater";
  53297. case ValueCondition._IsLesser: return "IsLesser";
  53298. default: return "";
  53299. }
  53300. };
  53301. /**
  53302. * Internal only
  53303. * @hidden
  53304. */
  53305. ValueCondition._IsEqual = 0;
  53306. /**
  53307. * Internal only
  53308. * @hidden
  53309. */
  53310. ValueCondition._IsDifferent = 1;
  53311. /**
  53312. * Internal only
  53313. * @hidden
  53314. */
  53315. ValueCondition._IsGreater = 2;
  53316. /**
  53317. * Internal only
  53318. * @hidden
  53319. */
  53320. ValueCondition._IsLesser = 3;
  53321. return ValueCondition;
  53322. }(Condition));
  53323. BABYLON.ValueCondition = ValueCondition;
  53324. /**
  53325. * Defines a predicate condition as an extension of Condition
  53326. */
  53327. var PredicateCondition = /** @class */ (function (_super) {
  53328. __extends(PredicateCondition, _super);
  53329. /**
  53330. * Creates a new PredicateCondition
  53331. * @param actionManager manager for the action the condition applies to
  53332. * @param predicate defines the predicate function used to validate the condition
  53333. */
  53334. function PredicateCondition(actionManager,
  53335. /** defines the predicate function used to validate the condition */
  53336. predicate) {
  53337. var _this = _super.call(this, actionManager) || this;
  53338. _this.predicate = predicate;
  53339. return _this;
  53340. }
  53341. /**
  53342. * @returns the validity of the predicate condition
  53343. */
  53344. PredicateCondition.prototype.isValid = function () {
  53345. return this.predicate();
  53346. };
  53347. return PredicateCondition;
  53348. }(Condition));
  53349. BABYLON.PredicateCondition = PredicateCondition;
  53350. /**
  53351. * Defines a state condition as an extension of Condition
  53352. */
  53353. var StateCondition = /** @class */ (function (_super) {
  53354. __extends(StateCondition, _super);
  53355. /**
  53356. * Creates a new StateCondition
  53357. * @param actionManager manager for the action the condition applies to
  53358. * @param target of the condition
  53359. * @param value to compare with target state
  53360. */
  53361. function StateCondition(actionManager, target, value) {
  53362. var _this = _super.call(this, actionManager) || this;
  53363. _this.value = value;
  53364. _this._target = target;
  53365. return _this;
  53366. }
  53367. /**
  53368. * @returns the validity of the state
  53369. */
  53370. StateCondition.prototype.isValid = function () {
  53371. return this._target.state === this.value;
  53372. };
  53373. /**
  53374. * Serialize the StateCondition into a JSON compatible object
  53375. * @returns serialization object
  53376. */
  53377. StateCondition.prototype.serialize = function () {
  53378. return this._serialize({
  53379. name: "StateCondition",
  53380. properties: [
  53381. BABYLON.Action._GetTargetProperty(this._target),
  53382. { name: "value", value: this.value }
  53383. ]
  53384. });
  53385. };
  53386. return StateCondition;
  53387. }(Condition));
  53388. BABYLON.StateCondition = StateCondition;
  53389. })(BABYLON || (BABYLON = {}));
  53390. //# sourceMappingURL=babylon.condition.js.map
  53391. var BABYLON;
  53392. (function (BABYLON) {
  53393. /**
  53394. * The action to be carried out following a trigger
  53395. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53396. */
  53397. var Action = /** @class */ (function () {
  53398. /**
  53399. * Creates a new Action
  53400. * @param triggerOptions the trigger, with or without parameters, for the action
  53401. * @param condition an optional determinant of action
  53402. */
  53403. function Action(
  53404. /** the trigger, with or without parameters, for the action */
  53405. triggerOptions, condition) {
  53406. this.triggerOptions = triggerOptions;
  53407. /**
  53408. * An event triggered prior to action being executed.
  53409. */
  53410. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53411. if (triggerOptions.parameter) {
  53412. this.trigger = triggerOptions.trigger;
  53413. this._triggerParameter = triggerOptions.parameter;
  53414. }
  53415. else {
  53416. this.trigger = triggerOptions;
  53417. }
  53418. this._nextActiveAction = this;
  53419. this._condition = condition;
  53420. }
  53421. /**
  53422. * Internal only
  53423. * @hidden
  53424. */
  53425. Action.prototype._prepare = function () {
  53426. };
  53427. /**
  53428. * Gets the trigger parameters
  53429. * @returns the trigger parameters
  53430. */
  53431. Action.prototype.getTriggerParameter = function () {
  53432. return this._triggerParameter;
  53433. };
  53434. /**
  53435. * Internal only - executes current action event
  53436. * @hidden
  53437. */
  53438. Action.prototype._executeCurrent = function (evt) {
  53439. if (this._nextActiveAction._condition) {
  53440. var condition = this._nextActiveAction._condition;
  53441. var currentRenderId = this._actionManager.getScene().getRenderId();
  53442. // We cache the current evaluation for the current frame
  53443. if (condition._evaluationId === currentRenderId) {
  53444. if (!condition._currentResult) {
  53445. return;
  53446. }
  53447. }
  53448. else {
  53449. condition._evaluationId = currentRenderId;
  53450. if (!condition.isValid()) {
  53451. condition._currentResult = false;
  53452. return;
  53453. }
  53454. condition._currentResult = true;
  53455. }
  53456. }
  53457. this.onBeforeExecuteObservable.notifyObservers(this);
  53458. this._nextActiveAction.execute(evt);
  53459. this.skipToNextActiveAction();
  53460. };
  53461. /**
  53462. * Execute placeholder for child classes
  53463. * @param evt optional action event
  53464. */
  53465. Action.prototype.execute = function (evt) {
  53466. };
  53467. /**
  53468. * Skips to next active action
  53469. */
  53470. Action.prototype.skipToNextActiveAction = function () {
  53471. if (this._nextActiveAction._child) {
  53472. if (!this._nextActiveAction._child._actionManager) {
  53473. this._nextActiveAction._child._actionManager = this._actionManager;
  53474. }
  53475. this._nextActiveAction = this._nextActiveAction._child;
  53476. }
  53477. else {
  53478. this._nextActiveAction = this;
  53479. }
  53480. };
  53481. /**
  53482. * Adds action to chain of actions, may be a DoNothingAction
  53483. * @param action defines the next action to execute
  53484. * @returns The action passed in
  53485. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53486. */
  53487. Action.prototype.then = function (action) {
  53488. this._child = action;
  53489. action._actionManager = this._actionManager;
  53490. action._prepare();
  53491. return action;
  53492. };
  53493. /**
  53494. * Internal only
  53495. * @hidden
  53496. */
  53497. Action.prototype._getProperty = function (propertyPath) {
  53498. return this._actionManager._getProperty(propertyPath);
  53499. };
  53500. /**
  53501. * Internal only
  53502. * @hidden
  53503. */
  53504. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53505. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53506. };
  53507. /**
  53508. * Serialize placeholder for child classes
  53509. * @param parent of child
  53510. * @returns the serialized object
  53511. */
  53512. Action.prototype.serialize = function (parent) {
  53513. };
  53514. /**
  53515. * Internal only called by serialize
  53516. * @hidden
  53517. */
  53518. Action.prototype._serialize = function (serializedAction, parent) {
  53519. var serializationObject = {
  53520. type: 1,
  53521. children: [],
  53522. name: serializedAction.name,
  53523. properties: serializedAction.properties || []
  53524. };
  53525. // Serialize child
  53526. if (this._child) {
  53527. this._child.serialize(serializationObject);
  53528. }
  53529. // Check if "this" has a condition
  53530. if (this._condition) {
  53531. var serializedCondition = this._condition.serialize();
  53532. serializedCondition.children.push(serializationObject);
  53533. if (parent) {
  53534. parent.children.push(serializedCondition);
  53535. }
  53536. return serializedCondition;
  53537. }
  53538. if (parent) {
  53539. parent.children.push(serializationObject);
  53540. }
  53541. return serializationObject;
  53542. };
  53543. /**
  53544. * Internal only
  53545. * @hidden
  53546. */
  53547. Action._SerializeValueAsString = function (value) {
  53548. if (typeof value === "number") {
  53549. return value.toString();
  53550. }
  53551. if (typeof value === "boolean") {
  53552. return value ? "true" : "false";
  53553. }
  53554. if (value instanceof BABYLON.Vector2) {
  53555. return value.x + ", " + value.y;
  53556. }
  53557. if (value instanceof BABYLON.Vector3) {
  53558. return value.x + ", " + value.y + ", " + value.z;
  53559. }
  53560. if (value instanceof BABYLON.Color3) {
  53561. return value.r + ", " + value.g + ", " + value.b;
  53562. }
  53563. if (value instanceof BABYLON.Color4) {
  53564. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53565. }
  53566. return value; // string
  53567. };
  53568. /**
  53569. * Internal only
  53570. * @hidden
  53571. */
  53572. Action._GetTargetProperty = function (target) {
  53573. return {
  53574. name: "target",
  53575. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53576. : target instanceof BABYLON.Light ? "LightProperties"
  53577. : target instanceof BABYLON.Camera ? "CameraProperties"
  53578. : "SceneProperties",
  53579. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53580. };
  53581. };
  53582. return Action;
  53583. }());
  53584. BABYLON.Action = Action;
  53585. })(BABYLON || (BABYLON = {}));
  53586. //# sourceMappingURL=babylon.action.js.map
  53587. var BABYLON;
  53588. (function (BABYLON) {
  53589. /**
  53590. * ActionEvent is the event being sent when an action is triggered.
  53591. */
  53592. var ActionEvent = /** @class */ (function () {
  53593. /**
  53594. * Creates a new ActionEvent
  53595. * @param source The mesh or sprite that triggered the action
  53596. * @param pointerX The X mouse cursor position at the time of the event
  53597. * @param pointerY The Y mouse cursor position at the time of the event
  53598. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53599. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53600. * @param additionalData additional data for the event
  53601. */
  53602. function ActionEvent(
  53603. /** The mesh or sprite that triggered the action */
  53604. source,
  53605. /** The X mouse cursor position at the time of the event */
  53606. pointerX,
  53607. /** The Y mouse cursor position at the time of the event */
  53608. pointerY,
  53609. /** The mesh that is currently pointed at (can be null) */
  53610. meshUnderPointer,
  53611. /** the original (browser) event that triggered the ActionEvent */
  53612. sourceEvent,
  53613. /** additional data for the event */
  53614. additionalData) {
  53615. this.source = source;
  53616. this.pointerX = pointerX;
  53617. this.pointerY = pointerY;
  53618. this.meshUnderPointer = meshUnderPointer;
  53619. this.sourceEvent = sourceEvent;
  53620. this.additionalData = additionalData;
  53621. }
  53622. /**
  53623. * Helper function to auto-create an ActionEvent from a source mesh.
  53624. * @param source The source mesh that triggered the event
  53625. * @param evt The original (browser) event
  53626. * @param additionalData additional data for the event
  53627. * @returns the new ActionEvent
  53628. */
  53629. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53630. var scene = source.getScene();
  53631. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53632. };
  53633. /**
  53634. * Helper function to auto-create an ActionEvent from a source sprite
  53635. * @param source The source sprite that triggered the event
  53636. * @param scene Scene associated with the sprite
  53637. * @param evt The original (browser) event
  53638. * @param additionalData additional data for the event
  53639. * @returns the new ActionEvent
  53640. */
  53641. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53642. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53643. };
  53644. /**
  53645. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53646. * @param scene the scene where the event occurred
  53647. * @param evt The original (browser) event
  53648. * @returns the new ActionEvent
  53649. */
  53650. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53651. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53652. };
  53653. /**
  53654. * Helper function to auto-create an ActionEvent from a primitive
  53655. * @param prim defines the target primitive
  53656. * @param pointerPos defines the pointer position
  53657. * @param evt The original (browser) event
  53658. * @param additionalData additional data for the event
  53659. * @returns the new ActionEvent
  53660. */
  53661. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53662. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53663. };
  53664. return ActionEvent;
  53665. }());
  53666. BABYLON.ActionEvent = ActionEvent;
  53667. /**
  53668. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53669. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53670. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53671. */
  53672. var ActionManager = /** @class */ (function () {
  53673. /**
  53674. * Creates a new action manager
  53675. * @param scene defines the hosting scene
  53676. */
  53677. function ActionManager(scene) {
  53678. // Members
  53679. /** Gets the list of actions */
  53680. this.actions = new Array();
  53681. /** Gets the cursor to use when hovering items */
  53682. this.hoverCursor = '';
  53683. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53684. scene._actionManagers.push(this);
  53685. }
  53686. Object.defineProperty(ActionManager, "NothingTrigger", {
  53687. /**
  53688. * Nothing
  53689. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53690. */
  53691. get: function () {
  53692. return ActionManager._NothingTrigger;
  53693. },
  53694. enumerable: true,
  53695. configurable: true
  53696. });
  53697. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53698. /**
  53699. * On pick
  53700. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53701. */
  53702. get: function () {
  53703. return ActionManager._OnPickTrigger;
  53704. },
  53705. enumerable: true,
  53706. configurable: true
  53707. });
  53708. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53709. /**
  53710. * On left pick
  53711. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53712. */
  53713. get: function () {
  53714. return ActionManager._OnLeftPickTrigger;
  53715. },
  53716. enumerable: true,
  53717. configurable: true
  53718. });
  53719. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53720. /**
  53721. * On right pick
  53722. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53723. */
  53724. get: function () {
  53725. return ActionManager._OnRightPickTrigger;
  53726. },
  53727. enumerable: true,
  53728. configurable: true
  53729. });
  53730. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53731. /**
  53732. * On center pick
  53733. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53734. */
  53735. get: function () {
  53736. return ActionManager._OnCenterPickTrigger;
  53737. },
  53738. enumerable: true,
  53739. configurable: true
  53740. });
  53741. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53742. /**
  53743. * On pick down
  53744. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53745. */
  53746. get: function () {
  53747. return ActionManager._OnPickDownTrigger;
  53748. },
  53749. enumerable: true,
  53750. configurable: true
  53751. });
  53752. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53753. /**
  53754. * On double pick
  53755. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53756. */
  53757. get: function () {
  53758. return ActionManager._OnDoublePickTrigger;
  53759. },
  53760. enumerable: true,
  53761. configurable: true
  53762. });
  53763. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53764. /**
  53765. * On pick up
  53766. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53767. */
  53768. get: function () {
  53769. return ActionManager._OnPickUpTrigger;
  53770. },
  53771. enumerable: true,
  53772. configurable: true
  53773. });
  53774. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53775. /**
  53776. * On pick out.
  53777. * This trigger will only be raised if you also declared a OnPickDown
  53778. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53779. */
  53780. get: function () {
  53781. return ActionManager._OnPickOutTrigger;
  53782. },
  53783. enumerable: true,
  53784. configurable: true
  53785. });
  53786. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53787. /**
  53788. * On long press
  53789. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53790. */
  53791. get: function () {
  53792. return ActionManager._OnLongPressTrigger;
  53793. },
  53794. enumerable: true,
  53795. configurable: true
  53796. });
  53797. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53798. /**
  53799. * On pointer over
  53800. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53801. */
  53802. get: function () {
  53803. return ActionManager._OnPointerOverTrigger;
  53804. },
  53805. enumerable: true,
  53806. configurable: true
  53807. });
  53808. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53809. /**
  53810. * On pointer out
  53811. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53812. */
  53813. get: function () {
  53814. return ActionManager._OnPointerOutTrigger;
  53815. },
  53816. enumerable: true,
  53817. configurable: true
  53818. });
  53819. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53820. /**
  53821. * On every frame
  53822. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53823. */
  53824. get: function () {
  53825. return ActionManager._OnEveryFrameTrigger;
  53826. },
  53827. enumerable: true,
  53828. configurable: true
  53829. });
  53830. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53831. /**
  53832. * On intersection enter
  53833. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53834. */
  53835. get: function () {
  53836. return ActionManager._OnIntersectionEnterTrigger;
  53837. },
  53838. enumerable: true,
  53839. configurable: true
  53840. });
  53841. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53842. /**
  53843. * On intersection exit
  53844. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53845. */
  53846. get: function () {
  53847. return ActionManager._OnIntersectionExitTrigger;
  53848. },
  53849. enumerable: true,
  53850. configurable: true
  53851. });
  53852. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53853. /**
  53854. * On key down
  53855. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53856. */
  53857. get: function () {
  53858. return ActionManager._OnKeyDownTrigger;
  53859. },
  53860. enumerable: true,
  53861. configurable: true
  53862. });
  53863. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53864. /**
  53865. * On key up
  53866. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53867. */
  53868. get: function () {
  53869. return ActionManager._OnKeyUpTrigger;
  53870. },
  53871. enumerable: true,
  53872. configurable: true
  53873. });
  53874. // Methods
  53875. /**
  53876. * Releases all associated resources
  53877. */
  53878. ActionManager.prototype.dispose = function () {
  53879. var index = this._scene._actionManagers.indexOf(this);
  53880. for (var i = 0; i < this.actions.length; i++) {
  53881. var action = this.actions[i];
  53882. ActionManager.Triggers[action.trigger]--;
  53883. if (ActionManager.Triggers[action.trigger] === 0) {
  53884. delete ActionManager.Triggers[action.trigger];
  53885. }
  53886. }
  53887. if (index > -1) {
  53888. this._scene._actionManagers.splice(index, 1);
  53889. }
  53890. };
  53891. /**
  53892. * Gets hosting scene
  53893. * @returns the hosting scene
  53894. */
  53895. ActionManager.prototype.getScene = function () {
  53896. return this._scene;
  53897. };
  53898. /**
  53899. * Does this action manager handles actions of any of the given triggers
  53900. * @param triggers defines the triggers to be tested
  53901. * @return a boolean indicating whether one (or more) of the triggers is handled
  53902. */
  53903. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53904. for (var index = 0; index < this.actions.length; index++) {
  53905. var action = this.actions[index];
  53906. if (triggers.indexOf(action.trigger) > -1) {
  53907. return true;
  53908. }
  53909. }
  53910. return false;
  53911. };
  53912. /**
  53913. * Does this action manager handles actions of a given trigger
  53914. * @param trigger defines the trigger to be tested
  53915. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53916. * @return whether the trigger is handled
  53917. */
  53918. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53919. for (var index = 0; index < this.actions.length; index++) {
  53920. var action = this.actions[index];
  53921. if (action.trigger === trigger) {
  53922. if (parameterPredicate) {
  53923. if (parameterPredicate(action.getTriggerParameter())) {
  53924. return true;
  53925. }
  53926. }
  53927. else {
  53928. return true;
  53929. }
  53930. }
  53931. }
  53932. return false;
  53933. };
  53934. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53935. /**
  53936. * Does this action manager has pointer triggers
  53937. */
  53938. get: function () {
  53939. for (var index = 0; index < this.actions.length; index++) {
  53940. var action = this.actions[index];
  53941. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53942. return true;
  53943. }
  53944. }
  53945. return false;
  53946. },
  53947. enumerable: true,
  53948. configurable: true
  53949. });
  53950. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53951. /**
  53952. * Does this action manager has pick triggers
  53953. */
  53954. get: function () {
  53955. for (var index = 0; index < this.actions.length; index++) {
  53956. var action = this.actions[index];
  53957. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53958. return true;
  53959. }
  53960. }
  53961. return false;
  53962. },
  53963. enumerable: true,
  53964. configurable: true
  53965. });
  53966. Object.defineProperty(ActionManager, "HasTriggers", {
  53967. /**
  53968. * Does exist one action manager with at least one trigger
  53969. **/
  53970. get: function () {
  53971. for (var t in ActionManager.Triggers) {
  53972. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53973. return true;
  53974. }
  53975. }
  53976. return false;
  53977. },
  53978. enumerable: true,
  53979. configurable: true
  53980. });
  53981. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53982. /**
  53983. * Does exist one action manager with at least one pick trigger
  53984. **/
  53985. get: function () {
  53986. for (var t in ActionManager.Triggers) {
  53987. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53988. var t_int = parseInt(t);
  53989. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53990. return true;
  53991. }
  53992. }
  53993. }
  53994. return false;
  53995. },
  53996. enumerable: true,
  53997. configurable: true
  53998. });
  53999. /**
  54000. * Does exist one action manager that handles actions of a given trigger
  54001. * @param trigger defines the trigger to be tested
  54002. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54003. **/
  54004. ActionManager.HasSpecificTrigger = function (trigger) {
  54005. for (var t in ActionManager.Triggers) {
  54006. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54007. var t_int = parseInt(t);
  54008. if (t_int === trigger) {
  54009. return true;
  54010. }
  54011. }
  54012. }
  54013. return false;
  54014. };
  54015. /**
  54016. * Registers an action to this action manager
  54017. * @param action defines the action to be registered
  54018. * @return the action amended (prepared) after registration
  54019. */
  54020. ActionManager.prototype.registerAction = function (action) {
  54021. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54022. if (this.getScene().actionManager !== this) {
  54023. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54024. return null;
  54025. }
  54026. }
  54027. this.actions.push(action);
  54028. if (ActionManager.Triggers[action.trigger]) {
  54029. ActionManager.Triggers[action.trigger]++;
  54030. }
  54031. else {
  54032. ActionManager.Triggers[action.trigger] = 1;
  54033. }
  54034. action._actionManager = this;
  54035. action._prepare();
  54036. return action;
  54037. };
  54038. /**
  54039. * Unregisters an action to this action manager
  54040. * @param action defines the action to be unregistered
  54041. * @return a boolean indicating whether the action has been unregistered
  54042. */
  54043. ActionManager.prototype.unregisterAction = function (action) {
  54044. var index = this.actions.indexOf(action);
  54045. if (index !== -1) {
  54046. this.actions.splice(index, 1);
  54047. ActionManager.Triggers[action.trigger] -= 1;
  54048. if (ActionManager.Triggers[action.trigger] === 0) {
  54049. delete ActionManager.Triggers[action.trigger];
  54050. }
  54051. delete action._actionManager;
  54052. return true;
  54053. }
  54054. return false;
  54055. };
  54056. /**
  54057. * Process a specific trigger
  54058. * @param trigger defines the trigger to process
  54059. * @param evt defines the event details to be processed
  54060. */
  54061. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54062. for (var index = 0; index < this.actions.length; index++) {
  54063. var action = this.actions[index];
  54064. if (action.trigger === trigger) {
  54065. if (evt) {
  54066. if (trigger === ActionManager.OnKeyUpTrigger
  54067. || trigger === ActionManager.OnKeyDownTrigger) {
  54068. var parameter = action.getTriggerParameter();
  54069. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54070. if (!parameter.toLowerCase) {
  54071. continue;
  54072. }
  54073. var lowerCase = parameter.toLowerCase();
  54074. if (lowerCase !== evt.sourceEvent.key) {
  54075. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54076. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54077. if (actualkey !== lowerCase) {
  54078. continue;
  54079. }
  54080. }
  54081. }
  54082. }
  54083. }
  54084. action._executeCurrent(evt);
  54085. }
  54086. }
  54087. };
  54088. /** @hidden */
  54089. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54090. var properties = propertyPath.split(".");
  54091. for (var index = 0; index < properties.length - 1; index++) {
  54092. target = target[properties[index]];
  54093. }
  54094. return target;
  54095. };
  54096. /** @hidden */
  54097. ActionManager.prototype._getProperty = function (propertyPath) {
  54098. var properties = propertyPath.split(".");
  54099. return properties[properties.length - 1];
  54100. };
  54101. /**
  54102. * Serialize this manager to a JSON object
  54103. * @param name defines the property name to store this manager
  54104. * @returns a JSON representation of this manager
  54105. */
  54106. ActionManager.prototype.serialize = function (name) {
  54107. var root = {
  54108. children: new Array(),
  54109. name: name,
  54110. type: 3,
  54111. properties: new Array() // Empty for root but required
  54112. };
  54113. for (var i = 0; i < this.actions.length; i++) {
  54114. var triggerObject = {
  54115. type: 0,
  54116. children: new Array(),
  54117. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54118. properties: new Array()
  54119. };
  54120. var triggerOptions = this.actions[i].triggerOptions;
  54121. if (triggerOptions && typeof triggerOptions !== "number") {
  54122. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54123. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54124. }
  54125. else {
  54126. var parameter = {};
  54127. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54128. if (triggerOptions.parameter.mesh) {
  54129. parameter._meshId = triggerOptions.parameter.mesh.id;
  54130. }
  54131. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54132. }
  54133. }
  54134. // Serialize child action, recursively
  54135. this.actions[i].serialize(triggerObject);
  54136. // Add serialized trigger
  54137. root.children.push(triggerObject);
  54138. }
  54139. return root;
  54140. };
  54141. /**
  54142. * Creates a new ActionManager from a JSON data
  54143. * @param parsedActions defines the JSON data to read from
  54144. * @param object defines the hosting mesh
  54145. * @param scene defines the hosting scene
  54146. */
  54147. ActionManager.Parse = function (parsedActions, object, scene) {
  54148. var actionManager = new ActionManager(scene);
  54149. if (object === null)
  54150. scene.actionManager = actionManager;
  54151. else
  54152. object.actionManager = actionManager;
  54153. // instanciate a new object
  54154. var instanciate = function (name, params) {
  54155. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54156. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54157. newInstance.constructor.apply(newInstance, params);
  54158. return newInstance;
  54159. };
  54160. var parseParameter = function (name, value, target, propertyPath) {
  54161. if (propertyPath === null) {
  54162. // String, boolean or float
  54163. var floatValue = parseFloat(value);
  54164. if (value === "true" || value === "false")
  54165. return value === "true";
  54166. else
  54167. return isNaN(floatValue) ? value : floatValue;
  54168. }
  54169. var effectiveTarget = propertyPath.split(".");
  54170. var values = value.split(",");
  54171. // Get effective Target
  54172. for (var i = 0; i < effectiveTarget.length; i++) {
  54173. target = target[effectiveTarget[i]];
  54174. }
  54175. // Return appropriate value with its type
  54176. if (typeof (target) === "boolean")
  54177. return values[0] === "true";
  54178. if (typeof (target) === "string")
  54179. return values[0];
  54180. // Parameters with multiple values such as Vector3 etc.
  54181. var split = new Array();
  54182. for (var i = 0; i < values.length; i++)
  54183. split.push(parseFloat(values[i]));
  54184. if (target instanceof BABYLON.Vector3)
  54185. return BABYLON.Vector3.FromArray(split);
  54186. if (target instanceof BABYLON.Vector4)
  54187. return BABYLON.Vector4.FromArray(split);
  54188. if (target instanceof BABYLON.Color3)
  54189. return BABYLON.Color3.FromArray(split);
  54190. if (target instanceof BABYLON.Color4)
  54191. return BABYLON.Color4.FromArray(split);
  54192. return parseFloat(values[0]);
  54193. };
  54194. // traverse graph per trigger
  54195. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54196. if (combineArray === void 0) { combineArray = null; }
  54197. if (parsedAction.detached)
  54198. return;
  54199. var parameters = new Array();
  54200. var target = null;
  54201. var propertyPath = null;
  54202. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54203. // Parameters
  54204. if (parsedAction.type === 2)
  54205. parameters.push(actionManager);
  54206. else
  54207. parameters.push(trigger);
  54208. if (combine) {
  54209. var actions = new Array();
  54210. for (var j = 0; j < parsedAction.combine.length; j++) {
  54211. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54212. }
  54213. parameters.push(actions);
  54214. }
  54215. else {
  54216. for (var i = 0; i < parsedAction.properties.length; i++) {
  54217. var value = parsedAction.properties[i].value;
  54218. var name = parsedAction.properties[i].name;
  54219. var targetType = parsedAction.properties[i].targetType;
  54220. if (name === "target")
  54221. if (targetType !== null && targetType === "SceneProperties")
  54222. value = target = scene;
  54223. else
  54224. value = target = scene.getNodeByName(value);
  54225. else if (name === "parent")
  54226. value = scene.getNodeByName(value);
  54227. else if (name === "sound")
  54228. value = scene.getSoundByName(value);
  54229. else if (name !== "propertyPath") {
  54230. if (parsedAction.type === 2 && name === "operator")
  54231. value = BABYLON.ValueCondition[value];
  54232. else
  54233. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54234. }
  54235. else {
  54236. propertyPath = value;
  54237. }
  54238. parameters.push(value);
  54239. }
  54240. }
  54241. if (combineArray === null) {
  54242. parameters.push(condition);
  54243. }
  54244. else {
  54245. parameters.push(null);
  54246. }
  54247. // If interpolate value action
  54248. if (parsedAction.name === "InterpolateValueAction") {
  54249. var param = parameters[parameters.length - 2];
  54250. parameters[parameters.length - 1] = param;
  54251. parameters[parameters.length - 2] = condition;
  54252. }
  54253. // Action or condition(s) and not CombineAction
  54254. var newAction = instanciate(parsedAction.name, parameters);
  54255. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54256. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54257. if (action)
  54258. action.then(nothing);
  54259. else
  54260. actionManager.registerAction(nothing);
  54261. action = nothing;
  54262. }
  54263. if (combineArray === null) {
  54264. if (newAction instanceof BABYLON.Condition) {
  54265. condition = newAction;
  54266. newAction = action;
  54267. }
  54268. else {
  54269. condition = null;
  54270. if (action)
  54271. action.then(newAction);
  54272. else
  54273. actionManager.registerAction(newAction);
  54274. }
  54275. }
  54276. else {
  54277. combineArray.push(newAction);
  54278. }
  54279. for (var i = 0; i < parsedAction.children.length; i++)
  54280. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54281. };
  54282. // triggers
  54283. for (var i = 0; i < parsedActions.children.length; i++) {
  54284. var triggerParams;
  54285. var trigger = parsedActions.children[i];
  54286. if (trigger.properties.length > 0) {
  54287. var param = trigger.properties[0].value;
  54288. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54289. if (value._meshId) {
  54290. value.mesh = scene.getMeshByID(value._meshId);
  54291. }
  54292. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54293. }
  54294. else
  54295. triggerParams = ActionManager[trigger.name];
  54296. for (var j = 0; j < trigger.children.length; j++) {
  54297. if (!trigger.detached)
  54298. traverse(trigger.children[j], triggerParams, null, null);
  54299. }
  54300. }
  54301. };
  54302. /**
  54303. * Get a trigger name by index
  54304. * @param trigger defines the trigger index
  54305. * @returns a trigger name
  54306. */
  54307. ActionManager.GetTriggerName = function (trigger) {
  54308. switch (trigger) {
  54309. case 0: return "NothingTrigger";
  54310. case 1: return "OnPickTrigger";
  54311. case 2: return "OnLeftPickTrigger";
  54312. case 3: return "OnRightPickTrigger";
  54313. case 4: return "OnCenterPickTrigger";
  54314. case 5: return "OnPickDownTrigger";
  54315. case 6: return "OnPickUpTrigger";
  54316. case 7: return "OnLongPressTrigger";
  54317. case 8: return "OnPointerOverTrigger";
  54318. case 9: return "OnPointerOutTrigger";
  54319. case 10: return "OnEveryFrameTrigger";
  54320. case 11: return "OnIntersectionEnterTrigger";
  54321. case 12: return "OnIntersectionExitTrigger";
  54322. case 13: return "OnKeyDownTrigger";
  54323. case 14: return "OnKeyUpTrigger";
  54324. case 15: return "OnPickOutTrigger";
  54325. default: return "";
  54326. }
  54327. };
  54328. // Statics
  54329. ActionManager._NothingTrigger = 0;
  54330. ActionManager._OnPickTrigger = 1;
  54331. ActionManager._OnLeftPickTrigger = 2;
  54332. ActionManager._OnRightPickTrigger = 3;
  54333. ActionManager._OnCenterPickTrigger = 4;
  54334. ActionManager._OnPickDownTrigger = 5;
  54335. ActionManager._OnDoublePickTrigger = 6;
  54336. ActionManager._OnPickUpTrigger = 7;
  54337. ActionManager._OnLongPressTrigger = 8;
  54338. ActionManager._OnPointerOverTrigger = 9;
  54339. ActionManager._OnPointerOutTrigger = 10;
  54340. ActionManager._OnEveryFrameTrigger = 11;
  54341. ActionManager._OnIntersectionEnterTrigger = 12;
  54342. ActionManager._OnIntersectionExitTrigger = 13;
  54343. ActionManager._OnKeyDownTrigger = 14;
  54344. ActionManager._OnKeyUpTrigger = 15;
  54345. ActionManager._OnPickOutTrigger = 16;
  54346. /** Gets the list of active triggers */
  54347. ActionManager.Triggers = {};
  54348. return ActionManager;
  54349. }());
  54350. BABYLON.ActionManager = ActionManager;
  54351. })(BABYLON || (BABYLON = {}));
  54352. //# sourceMappingURL=babylon.actionManager.js.map
  54353. var BABYLON;
  54354. (function (BABYLON) {
  54355. var InterpolateValueAction = /** @class */ (function (_super) {
  54356. __extends(InterpolateValueAction, _super);
  54357. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54358. if (duration === void 0) { duration = 1000; }
  54359. var _this = _super.call(this, triggerOptions, condition) || this;
  54360. _this.propertyPath = propertyPath;
  54361. _this.value = value;
  54362. _this.duration = duration;
  54363. _this.stopOtherAnimations = stopOtherAnimations;
  54364. _this.onInterpolationDone = onInterpolationDone;
  54365. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54366. _this._target = _this._effectiveTarget = target;
  54367. return _this;
  54368. }
  54369. InterpolateValueAction.prototype._prepare = function () {
  54370. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54371. this._property = this._getProperty(this.propertyPath);
  54372. };
  54373. InterpolateValueAction.prototype.execute = function () {
  54374. var _this = this;
  54375. var scene = this._actionManager.getScene();
  54376. var keys = [
  54377. {
  54378. frame: 0,
  54379. value: this._effectiveTarget[this._property]
  54380. }, {
  54381. frame: 100,
  54382. value: this.value
  54383. }
  54384. ];
  54385. var dataType;
  54386. if (typeof this.value === "number") {
  54387. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54388. }
  54389. else if (this.value instanceof BABYLON.Color3) {
  54390. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54391. }
  54392. else if (this.value instanceof BABYLON.Vector3) {
  54393. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54394. }
  54395. else if (this.value instanceof BABYLON.Matrix) {
  54396. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54397. }
  54398. else if (this.value instanceof BABYLON.Quaternion) {
  54399. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54400. }
  54401. else {
  54402. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54403. return;
  54404. }
  54405. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54406. animation.setKeys(keys);
  54407. if (this.stopOtherAnimations) {
  54408. scene.stopAnimation(this._effectiveTarget);
  54409. }
  54410. var wrapper = function () {
  54411. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54412. if (_this.onInterpolationDone) {
  54413. _this.onInterpolationDone();
  54414. }
  54415. };
  54416. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54417. };
  54418. InterpolateValueAction.prototype.serialize = function (parent) {
  54419. return _super.prototype._serialize.call(this, {
  54420. name: "InterpolateValueAction",
  54421. properties: [
  54422. BABYLON.Action._GetTargetProperty(this._target),
  54423. { name: "propertyPath", value: this.propertyPath },
  54424. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54425. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54426. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54427. ]
  54428. }, parent);
  54429. };
  54430. return InterpolateValueAction;
  54431. }(BABYLON.Action));
  54432. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54433. })(BABYLON || (BABYLON = {}));
  54434. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54435. var BABYLON;
  54436. (function (BABYLON) {
  54437. var SwitchBooleanAction = /** @class */ (function (_super) {
  54438. __extends(SwitchBooleanAction, _super);
  54439. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54440. var _this = _super.call(this, triggerOptions, condition) || this;
  54441. _this.propertyPath = propertyPath;
  54442. _this._target = _this._effectiveTarget = target;
  54443. return _this;
  54444. }
  54445. SwitchBooleanAction.prototype._prepare = function () {
  54446. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54447. this._property = this._getProperty(this.propertyPath);
  54448. };
  54449. SwitchBooleanAction.prototype.execute = function () {
  54450. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54451. };
  54452. SwitchBooleanAction.prototype.serialize = function (parent) {
  54453. return _super.prototype._serialize.call(this, {
  54454. name: "SwitchBooleanAction",
  54455. properties: [
  54456. BABYLON.Action._GetTargetProperty(this._target),
  54457. { name: "propertyPath", value: this.propertyPath }
  54458. ]
  54459. }, parent);
  54460. };
  54461. return SwitchBooleanAction;
  54462. }(BABYLON.Action));
  54463. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54464. var SetStateAction = /** @class */ (function (_super) {
  54465. __extends(SetStateAction, _super);
  54466. function SetStateAction(triggerOptions, target, value, condition) {
  54467. var _this = _super.call(this, triggerOptions, condition) || this;
  54468. _this.value = value;
  54469. _this._target = target;
  54470. return _this;
  54471. }
  54472. SetStateAction.prototype.execute = function () {
  54473. this._target.state = this.value;
  54474. };
  54475. SetStateAction.prototype.serialize = function (parent) {
  54476. return _super.prototype._serialize.call(this, {
  54477. name: "SetStateAction",
  54478. properties: [
  54479. BABYLON.Action._GetTargetProperty(this._target),
  54480. { name: "value", value: this.value }
  54481. ]
  54482. }, parent);
  54483. };
  54484. return SetStateAction;
  54485. }(BABYLON.Action));
  54486. BABYLON.SetStateAction = SetStateAction;
  54487. var SetValueAction = /** @class */ (function (_super) {
  54488. __extends(SetValueAction, _super);
  54489. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54490. var _this = _super.call(this, triggerOptions, condition) || this;
  54491. _this.propertyPath = propertyPath;
  54492. _this.value = value;
  54493. _this._target = _this._effectiveTarget = target;
  54494. return _this;
  54495. }
  54496. SetValueAction.prototype._prepare = function () {
  54497. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54498. this._property = this._getProperty(this.propertyPath);
  54499. };
  54500. SetValueAction.prototype.execute = function () {
  54501. this._effectiveTarget[this._property] = this.value;
  54502. if (this._target.markAsDirty) {
  54503. this._target.markAsDirty(this._property);
  54504. }
  54505. };
  54506. SetValueAction.prototype.serialize = function (parent) {
  54507. return _super.prototype._serialize.call(this, {
  54508. name: "SetValueAction",
  54509. properties: [
  54510. BABYLON.Action._GetTargetProperty(this._target),
  54511. { name: "propertyPath", value: this.propertyPath },
  54512. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54513. ]
  54514. }, parent);
  54515. };
  54516. return SetValueAction;
  54517. }(BABYLON.Action));
  54518. BABYLON.SetValueAction = SetValueAction;
  54519. var IncrementValueAction = /** @class */ (function (_super) {
  54520. __extends(IncrementValueAction, _super);
  54521. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54522. var _this = _super.call(this, triggerOptions, condition) || this;
  54523. _this.propertyPath = propertyPath;
  54524. _this.value = value;
  54525. _this._target = _this._effectiveTarget = target;
  54526. return _this;
  54527. }
  54528. IncrementValueAction.prototype._prepare = function () {
  54529. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54530. this._property = this._getProperty(this.propertyPath);
  54531. if (typeof this._effectiveTarget[this._property] !== "number") {
  54532. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54533. }
  54534. };
  54535. IncrementValueAction.prototype.execute = function () {
  54536. this._effectiveTarget[this._property] += this.value;
  54537. if (this._target.markAsDirty) {
  54538. this._target.markAsDirty(this._property);
  54539. }
  54540. };
  54541. IncrementValueAction.prototype.serialize = function (parent) {
  54542. return _super.prototype._serialize.call(this, {
  54543. name: "IncrementValueAction",
  54544. properties: [
  54545. BABYLON.Action._GetTargetProperty(this._target),
  54546. { name: "propertyPath", value: this.propertyPath },
  54547. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54548. ]
  54549. }, parent);
  54550. };
  54551. return IncrementValueAction;
  54552. }(BABYLON.Action));
  54553. BABYLON.IncrementValueAction = IncrementValueAction;
  54554. var PlayAnimationAction = /** @class */ (function (_super) {
  54555. __extends(PlayAnimationAction, _super);
  54556. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54557. var _this = _super.call(this, triggerOptions, condition) || this;
  54558. _this.from = from;
  54559. _this.to = to;
  54560. _this.loop = loop;
  54561. _this._target = target;
  54562. return _this;
  54563. }
  54564. PlayAnimationAction.prototype._prepare = function () {
  54565. };
  54566. PlayAnimationAction.prototype.execute = function () {
  54567. var scene = this._actionManager.getScene();
  54568. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54569. };
  54570. PlayAnimationAction.prototype.serialize = function (parent) {
  54571. return _super.prototype._serialize.call(this, {
  54572. name: "PlayAnimationAction",
  54573. properties: [
  54574. BABYLON.Action._GetTargetProperty(this._target),
  54575. { name: "from", value: String(this.from) },
  54576. { name: "to", value: String(this.to) },
  54577. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54578. ]
  54579. }, parent);
  54580. };
  54581. return PlayAnimationAction;
  54582. }(BABYLON.Action));
  54583. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54584. var StopAnimationAction = /** @class */ (function (_super) {
  54585. __extends(StopAnimationAction, _super);
  54586. function StopAnimationAction(triggerOptions, target, condition) {
  54587. var _this = _super.call(this, triggerOptions, condition) || this;
  54588. _this._target = target;
  54589. return _this;
  54590. }
  54591. StopAnimationAction.prototype._prepare = function () {
  54592. };
  54593. StopAnimationAction.prototype.execute = function () {
  54594. var scene = this._actionManager.getScene();
  54595. scene.stopAnimation(this._target);
  54596. };
  54597. StopAnimationAction.prototype.serialize = function (parent) {
  54598. return _super.prototype._serialize.call(this, {
  54599. name: "StopAnimationAction",
  54600. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54601. }, parent);
  54602. };
  54603. return StopAnimationAction;
  54604. }(BABYLON.Action));
  54605. BABYLON.StopAnimationAction = StopAnimationAction;
  54606. var DoNothingAction = /** @class */ (function (_super) {
  54607. __extends(DoNothingAction, _super);
  54608. function DoNothingAction(triggerOptions, condition) {
  54609. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54610. return _super.call(this, triggerOptions, condition) || this;
  54611. }
  54612. DoNothingAction.prototype.execute = function () {
  54613. };
  54614. DoNothingAction.prototype.serialize = function (parent) {
  54615. return _super.prototype._serialize.call(this, {
  54616. name: "DoNothingAction",
  54617. properties: []
  54618. }, parent);
  54619. };
  54620. return DoNothingAction;
  54621. }(BABYLON.Action));
  54622. BABYLON.DoNothingAction = DoNothingAction;
  54623. var CombineAction = /** @class */ (function (_super) {
  54624. __extends(CombineAction, _super);
  54625. function CombineAction(triggerOptions, children, condition) {
  54626. var _this = _super.call(this, triggerOptions, condition) || this;
  54627. _this.children = children;
  54628. return _this;
  54629. }
  54630. CombineAction.prototype._prepare = function () {
  54631. for (var index = 0; index < this.children.length; index++) {
  54632. this.children[index]._actionManager = this._actionManager;
  54633. this.children[index]._prepare();
  54634. }
  54635. };
  54636. CombineAction.prototype.execute = function (evt) {
  54637. for (var index = 0; index < this.children.length; index++) {
  54638. this.children[index].execute(evt);
  54639. }
  54640. };
  54641. CombineAction.prototype.serialize = function (parent) {
  54642. var serializationObject = _super.prototype._serialize.call(this, {
  54643. name: "CombineAction",
  54644. properties: [],
  54645. combine: []
  54646. }, parent);
  54647. for (var i = 0; i < this.children.length; i++) {
  54648. serializationObject.combine.push(this.children[i].serialize(null));
  54649. }
  54650. return serializationObject;
  54651. };
  54652. return CombineAction;
  54653. }(BABYLON.Action));
  54654. BABYLON.CombineAction = CombineAction;
  54655. var ExecuteCodeAction = /** @class */ (function (_super) {
  54656. __extends(ExecuteCodeAction, _super);
  54657. function ExecuteCodeAction(triggerOptions, func, condition) {
  54658. var _this = _super.call(this, triggerOptions, condition) || this;
  54659. _this.func = func;
  54660. return _this;
  54661. }
  54662. ExecuteCodeAction.prototype.execute = function (evt) {
  54663. this.func(evt);
  54664. };
  54665. return ExecuteCodeAction;
  54666. }(BABYLON.Action));
  54667. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54668. var SetParentAction = /** @class */ (function (_super) {
  54669. __extends(SetParentAction, _super);
  54670. function SetParentAction(triggerOptions, target, parent, condition) {
  54671. var _this = _super.call(this, triggerOptions, condition) || this;
  54672. _this._target = target;
  54673. _this._parent = parent;
  54674. return _this;
  54675. }
  54676. SetParentAction.prototype._prepare = function () {
  54677. };
  54678. SetParentAction.prototype.execute = function () {
  54679. if (this._target.parent === this._parent) {
  54680. return;
  54681. }
  54682. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54683. invertParentWorldMatrix.invert();
  54684. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54685. this._target.parent = this._parent;
  54686. };
  54687. SetParentAction.prototype.serialize = function (parent) {
  54688. return _super.prototype._serialize.call(this, {
  54689. name: "SetParentAction",
  54690. properties: [
  54691. BABYLON.Action._GetTargetProperty(this._target),
  54692. BABYLON.Action._GetTargetProperty(this._parent),
  54693. ]
  54694. }, parent);
  54695. };
  54696. return SetParentAction;
  54697. }(BABYLON.Action));
  54698. BABYLON.SetParentAction = SetParentAction;
  54699. var PlaySoundAction = /** @class */ (function (_super) {
  54700. __extends(PlaySoundAction, _super);
  54701. function PlaySoundAction(triggerOptions, sound, condition) {
  54702. var _this = _super.call(this, triggerOptions, condition) || this;
  54703. _this._sound = sound;
  54704. return _this;
  54705. }
  54706. PlaySoundAction.prototype._prepare = function () {
  54707. };
  54708. PlaySoundAction.prototype.execute = function () {
  54709. if (this._sound !== undefined)
  54710. this._sound.play();
  54711. };
  54712. PlaySoundAction.prototype.serialize = function (parent) {
  54713. return _super.prototype._serialize.call(this, {
  54714. name: "PlaySoundAction",
  54715. properties: [{ name: "sound", value: this._sound.name }]
  54716. }, parent);
  54717. };
  54718. return PlaySoundAction;
  54719. }(BABYLON.Action));
  54720. BABYLON.PlaySoundAction = PlaySoundAction;
  54721. var StopSoundAction = /** @class */ (function (_super) {
  54722. __extends(StopSoundAction, _super);
  54723. function StopSoundAction(triggerOptions, sound, condition) {
  54724. var _this = _super.call(this, triggerOptions, condition) || this;
  54725. _this._sound = sound;
  54726. return _this;
  54727. }
  54728. StopSoundAction.prototype._prepare = function () {
  54729. };
  54730. StopSoundAction.prototype.execute = function () {
  54731. if (this._sound !== undefined)
  54732. this._sound.stop();
  54733. };
  54734. StopSoundAction.prototype.serialize = function (parent) {
  54735. return _super.prototype._serialize.call(this, {
  54736. name: "StopSoundAction",
  54737. properties: [{ name: "sound", value: this._sound.name }]
  54738. }, parent);
  54739. };
  54740. return StopSoundAction;
  54741. }(BABYLON.Action));
  54742. BABYLON.StopSoundAction = StopSoundAction;
  54743. })(BABYLON || (BABYLON = {}));
  54744. //# sourceMappingURL=babylon.directActions.js.map
  54745. var BABYLON;
  54746. (function (BABYLON) {
  54747. var SpriteManager = /** @class */ (function () {
  54748. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54749. if (epsilon === void 0) { epsilon = 0.01; }
  54750. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54751. this.name = name;
  54752. this.sprites = new Array();
  54753. this.renderingGroupId = 0;
  54754. this.layerMask = 0x0FFFFFFF;
  54755. this.fogEnabled = true;
  54756. this.isPickable = false;
  54757. /**
  54758. * An event triggered when the manager is disposed.
  54759. */
  54760. this.onDisposeObservable = new BABYLON.Observable();
  54761. this._vertexBuffers = {};
  54762. this._capacity = capacity;
  54763. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54764. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54765. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54766. if (cellSize.width && cellSize.height) {
  54767. this.cellWidth = cellSize.width;
  54768. this.cellHeight = cellSize.height;
  54769. }
  54770. else if (cellSize !== undefined) {
  54771. this.cellWidth = cellSize;
  54772. this.cellHeight = cellSize;
  54773. }
  54774. else {
  54775. return;
  54776. }
  54777. this._epsilon = epsilon;
  54778. this._scene = scene;
  54779. this._scene.spriteManagers.push(this);
  54780. var indices = [];
  54781. var index = 0;
  54782. for (var count = 0; count < capacity; count++) {
  54783. indices.push(index);
  54784. indices.push(index + 1);
  54785. indices.push(index + 2);
  54786. indices.push(index);
  54787. indices.push(index + 2);
  54788. indices.push(index + 3);
  54789. index += 4;
  54790. }
  54791. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54792. // VBO
  54793. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54794. this._vertexData = new Float32Array(capacity * 16 * 4);
  54795. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54796. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54797. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54798. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54799. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54800. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54801. this._vertexBuffers["options"] = options;
  54802. this._vertexBuffers["cellInfo"] = cellInfo;
  54803. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54804. // Effects
  54805. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54806. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54807. }
  54808. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54809. set: function (callback) {
  54810. if (this._onDisposeObserver) {
  54811. this.onDisposeObservable.remove(this._onDisposeObserver);
  54812. }
  54813. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54814. },
  54815. enumerable: true,
  54816. configurable: true
  54817. });
  54818. Object.defineProperty(SpriteManager.prototype, "texture", {
  54819. get: function () {
  54820. return this._spriteTexture;
  54821. },
  54822. set: function (value) {
  54823. this._spriteTexture = value;
  54824. },
  54825. enumerable: true,
  54826. configurable: true
  54827. });
  54828. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54829. var arrayOffset = index * 16;
  54830. if (offsetX === 0)
  54831. offsetX = this._epsilon;
  54832. else if (offsetX === 1)
  54833. offsetX = 1 - this._epsilon;
  54834. if (offsetY === 0)
  54835. offsetY = this._epsilon;
  54836. else if (offsetY === 1)
  54837. offsetY = 1 - this._epsilon;
  54838. this._vertexData[arrayOffset] = sprite.position.x;
  54839. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54840. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54841. this._vertexData[arrayOffset + 3] = sprite.angle;
  54842. this._vertexData[arrayOffset + 4] = sprite.width;
  54843. this._vertexData[arrayOffset + 5] = sprite.height;
  54844. this._vertexData[arrayOffset + 6] = offsetX;
  54845. this._vertexData[arrayOffset + 7] = offsetY;
  54846. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54847. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54848. var offset = (sprite.cellIndex / rowSize) >> 0;
  54849. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54850. this._vertexData[arrayOffset + 11] = offset;
  54851. // Color
  54852. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54853. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54854. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54855. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54856. };
  54857. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54858. var count = Math.min(this._capacity, this.sprites.length);
  54859. var min = BABYLON.Vector3.Zero();
  54860. var max = BABYLON.Vector3.Zero();
  54861. var distance = Number.MAX_VALUE;
  54862. var currentSprite = null;
  54863. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54864. var cameraView = camera.getViewMatrix();
  54865. for (var index = 0; index < count; index++) {
  54866. var sprite = this.sprites[index];
  54867. if (!sprite) {
  54868. continue;
  54869. }
  54870. if (predicate) {
  54871. if (!predicate(sprite)) {
  54872. continue;
  54873. }
  54874. }
  54875. else if (!sprite.isPickable) {
  54876. continue;
  54877. }
  54878. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54879. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54880. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54881. if (ray.intersectsBoxMinMax(min, max)) {
  54882. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54883. if (distance > currentDistance) {
  54884. distance = currentDistance;
  54885. currentSprite = sprite;
  54886. if (fastCheck) {
  54887. break;
  54888. }
  54889. }
  54890. }
  54891. }
  54892. if (currentSprite) {
  54893. var result = new BABYLON.PickingInfo();
  54894. result.hit = true;
  54895. result.pickedSprite = currentSprite;
  54896. result.distance = distance;
  54897. return result;
  54898. }
  54899. return null;
  54900. };
  54901. SpriteManager.prototype.render = function () {
  54902. // Check
  54903. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54904. return;
  54905. var engine = this._scene.getEngine();
  54906. var baseSize = this._spriteTexture.getBaseSize();
  54907. // Sprites
  54908. var deltaTime = engine.getDeltaTime();
  54909. var max = Math.min(this._capacity, this.sprites.length);
  54910. var rowSize = baseSize.width / this.cellWidth;
  54911. var offset = 0;
  54912. for (var index = 0; index < max; index++) {
  54913. var sprite = this.sprites[index];
  54914. if (!sprite) {
  54915. continue;
  54916. }
  54917. sprite._animate(deltaTime);
  54918. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54919. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54920. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54921. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54922. }
  54923. this._buffer.update(this._vertexData);
  54924. // Render
  54925. var effect = this._effectBase;
  54926. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54927. effect = this._effectFog;
  54928. }
  54929. engine.enableEffect(effect);
  54930. var viewMatrix = this._scene.getViewMatrix();
  54931. effect.setTexture("diffuseSampler", this._spriteTexture);
  54932. effect.setMatrix("view", viewMatrix);
  54933. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54934. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54935. // Fog
  54936. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54937. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54938. effect.setColor3("vFogColor", this._scene.fogColor);
  54939. }
  54940. // VBOs
  54941. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54942. // Draw order
  54943. engine.setDepthFunctionToLessOrEqual();
  54944. effect.setBool("alphaTest", true);
  54945. engine.setColorWrite(false);
  54946. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54947. engine.setColorWrite(true);
  54948. effect.setBool("alphaTest", false);
  54949. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54950. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54951. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54952. };
  54953. SpriteManager.prototype.dispose = function () {
  54954. if (this._buffer) {
  54955. this._buffer.dispose();
  54956. this._buffer = null;
  54957. }
  54958. if (this._indexBuffer) {
  54959. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54960. this._indexBuffer = null;
  54961. }
  54962. if (this._spriteTexture) {
  54963. this._spriteTexture.dispose();
  54964. this._spriteTexture = null;
  54965. }
  54966. // Remove from scene
  54967. var index = this._scene.spriteManagers.indexOf(this);
  54968. this._scene.spriteManagers.splice(index, 1);
  54969. // Callback
  54970. this.onDisposeObservable.notifyObservers(this);
  54971. this.onDisposeObservable.clear();
  54972. };
  54973. return SpriteManager;
  54974. }());
  54975. BABYLON.SpriteManager = SpriteManager;
  54976. })(BABYLON || (BABYLON = {}));
  54977. //# sourceMappingURL=babylon.spriteManager.js.map
  54978. var BABYLON;
  54979. (function (BABYLON) {
  54980. var Sprite = /** @class */ (function () {
  54981. function Sprite(name, manager) {
  54982. this.name = name;
  54983. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54984. this.width = 1.0;
  54985. this.height = 1.0;
  54986. this.angle = 0;
  54987. this.cellIndex = 0;
  54988. this.invertU = 0;
  54989. this.invertV = 0;
  54990. this.animations = new Array();
  54991. this.isPickable = false;
  54992. this._animationStarted = false;
  54993. this._loopAnimation = false;
  54994. this._fromIndex = 0;
  54995. this._toIndex = 0;
  54996. this._delay = 0;
  54997. this._direction = 1;
  54998. this._time = 0;
  54999. this._manager = manager;
  55000. this._manager.sprites.push(this);
  55001. this.position = BABYLON.Vector3.Zero();
  55002. }
  55003. Object.defineProperty(Sprite.prototype, "size", {
  55004. get: function () {
  55005. return this.width;
  55006. },
  55007. set: function (value) {
  55008. this.width = value;
  55009. this.height = value;
  55010. },
  55011. enumerable: true,
  55012. configurable: true
  55013. });
  55014. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55015. this._fromIndex = from;
  55016. this._toIndex = to;
  55017. this._loopAnimation = loop;
  55018. this._delay = delay;
  55019. this._animationStarted = true;
  55020. this._direction = from < to ? 1 : -1;
  55021. this.cellIndex = from;
  55022. this._time = 0;
  55023. this._onAnimationEnd = onAnimationEnd;
  55024. };
  55025. Sprite.prototype.stopAnimation = function () {
  55026. this._animationStarted = false;
  55027. };
  55028. Sprite.prototype._animate = function (deltaTime) {
  55029. if (!this._animationStarted)
  55030. return;
  55031. this._time += deltaTime;
  55032. if (this._time > this._delay) {
  55033. this._time = this._time % this._delay;
  55034. this.cellIndex += this._direction;
  55035. if (this.cellIndex > this._toIndex) {
  55036. if (this._loopAnimation) {
  55037. this.cellIndex = this._fromIndex;
  55038. }
  55039. else {
  55040. this.cellIndex = this._toIndex;
  55041. this._animationStarted = false;
  55042. if (this._onAnimationEnd) {
  55043. this._onAnimationEnd();
  55044. }
  55045. if (this.disposeWhenFinishedAnimating) {
  55046. this.dispose();
  55047. }
  55048. }
  55049. }
  55050. }
  55051. };
  55052. Sprite.prototype.dispose = function () {
  55053. for (var i = 0; i < this._manager.sprites.length; i++) {
  55054. if (this._manager.sprites[i] == this) {
  55055. this._manager.sprites.splice(i, 1);
  55056. }
  55057. }
  55058. };
  55059. return Sprite;
  55060. }());
  55061. BABYLON.Sprite = Sprite;
  55062. })(BABYLON || (BABYLON = {}));
  55063. //# sourceMappingURL=babylon.sprite.js.map
  55064. var BABYLON;
  55065. (function (BABYLON) {
  55066. var IntersectionInfo = /** @class */ (function () {
  55067. function IntersectionInfo(bu, bv, distance) {
  55068. this.bu = bu;
  55069. this.bv = bv;
  55070. this.distance = distance;
  55071. this.faceId = 0;
  55072. this.subMeshId = 0;
  55073. }
  55074. return IntersectionInfo;
  55075. }());
  55076. BABYLON.IntersectionInfo = IntersectionInfo;
  55077. /**
  55078. * Information about the result of picking within a scene
  55079. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55080. */
  55081. var PickingInfo = /** @class */ (function () {
  55082. function PickingInfo() {
  55083. /**
  55084. * If the pick collided with an object
  55085. */
  55086. this.hit = false;
  55087. /**
  55088. * Distance away where the pick collided
  55089. */
  55090. this.distance = 0;
  55091. /**
  55092. * The location of pick collision
  55093. */
  55094. this.pickedPoint = null;
  55095. /**
  55096. * The mesh corrisponding the the pick collision
  55097. */
  55098. this.pickedMesh = null;
  55099. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55100. this.bu = 0;
  55101. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55102. this.bv = 0;
  55103. /** The id of the face on the mesh that was picked */
  55104. this.faceId = -1;
  55105. /** Id of the the submesh that was picked */
  55106. this.subMeshId = 0;
  55107. /** If a sprite was picked, this will be the sprite the pick collided with */
  55108. this.pickedSprite = null;
  55109. /**
  55110. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55111. */
  55112. this.originMesh = null;
  55113. /**
  55114. * The ray that was used to perform the picking.
  55115. */
  55116. this.ray = null;
  55117. }
  55118. /**
  55119. * Gets the normal corrispodning to the face the pick collided with
  55120. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55121. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55122. * @returns The normal corrispodning to the face the pick collided with
  55123. */
  55124. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55125. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55126. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55127. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55128. return null;
  55129. }
  55130. var indices = this.pickedMesh.getIndices();
  55131. if (!indices) {
  55132. return null;
  55133. }
  55134. var result;
  55135. if (useVerticesNormals) {
  55136. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55137. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55138. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55139. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55140. normal0 = normal0.scale(this.bu);
  55141. normal1 = normal1.scale(this.bv);
  55142. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55143. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55144. }
  55145. else {
  55146. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55147. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55148. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55149. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55150. var p1p2 = vertex1.subtract(vertex2);
  55151. var p3p2 = vertex3.subtract(vertex2);
  55152. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55153. }
  55154. if (useWorldCoordinates) {
  55155. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  55156. }
  55157. return BABYLON.Vector3.Normalize(result);
  55158. };
  55159. /**
  55160. * Gets the texture coordinates of where the pick occured
  55161. * @returns the vector containing the coordnates of the texture
  55162. */
  55163. PickingInfo.prototype.getTextureCoordinates = function () {
  55164. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55165. return null;
  55166. }
  55167. var indices = this.pickedMesh.getIndices();
  55168. if (!indices) {
  55169. return null;
  55170. }
  55171. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55172. if (!uvs) {
  55173. return null;
  55174. }
  55175. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55176. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55177. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55178. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55179. uv1 = uv1.scale(this.bu);
  55180. uv2 = uv2.scale(this.bv);
  55181. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55182. };
  55183. return PickingInfo;
  55184. }());
  55185. BABYLON.PickingInfo = PickingInfo;
  55186. })(BABYLON || (BABYLON = {}));
  55187. //# sourceMappingURL=babylon.pickingInfo.js.map
  55188. var BABYLON;
  55189. (function (BABYLON) {
  55190. var Ray = /** @class */ (function () {
  55191. function Ray(origin, direction, length) {
  55192. if (length === void 0) { length = Number.MAX_VALUE; }
  55193. this.origin = origin;
  55194. this.direction = direction;
  55195. this.length = length;
  55196. }
  55197. // Methods
  55198. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55199. var d = 0.0;
  55200. var maxValue = Number.MAX_VALUE;
  55201. var inv;
  55202. var min;
  55203. var max;
  55204. var temp;
  55205. if (Math.abs(this.direction.x) < 0.0000001) {
  55206. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55207. return false;
  55208. }
  55209. }
  55210. else {
  55211. inv = 1.0 / this.direction.x;
  55212. min = (minimum.x - this.origin.x) * inv;
  55213. max = (maximum.x - this.origin.x) * inv;
  55214. if (max === -Infinity) {
  55215. max = Infinity;
  55216. }
  55217. if (min > max) {
  55218. temp = min;
  55219. min = max;
  55220. max = temp;
  55221. }
  55222. d = Math.max(min, d);
  55223. maxValue = Math.min(max, maxValue);
  55224. if (d > maxValue) {
  55225. return false;
  55226. }
  55227. }
  55228. if (Math.abs(this.direction.y) < 0.0000001) {
  55229. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55230. return false;
  55231. }
  55232. }
  55233. else {
  55234. inv = 1.0 / this.direction.y;
  55235. min = (minimum.y - this.origin.y) * inv;
  55236. max = (maximum.y - this.origin.y) * inv;
  55237. if (max === -Infinity) {
  55238. max = Infinity;
  55239. }
  55240. if (min > max) {
  55241. temp = min;
  55242. min = max;
  55243. max = temp;
  55244. }
  55245. d = Math.max(min, d);
  55246. maxValue = Math.min(max, maxValue);
  55247. if (d > maxValue) {
  55248. return false;
  55249. }
  55250. }
  55251. if (Math.abs(this.direction.z) < 0.0000001) {
  55252. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55253. return false;
  55254. }
  55255. }
  55256. else {
  55257. inv = 1.0 / this.direction.z;
  55258. min = (minimum.z - this.origin.z) * inv;
  55259. max = (maximum.z - this.origin.z) * inv;
  55260. if (max === -Infinity) {
  55261. max = Infinity;
  55262. }
  55263. if (min > max) {
  55264. temp = min;
  55265. min = max;
  55266. max = temp;
  55267. }
  55268. d = Math.max(min, d);
  55269. maxValue = Math.min(max, maxValue);
  55270. if (d > maxValue) {
  55271. return false;
  55272. }
  55273. }
  55274. return true;
  55275. };
  55276. Ray.prototype.intersectsBox = function (box) {
  55277. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55278. };
  55279. Ray.prototype.intersectsSphere = function (sphere) {
  55280. var x = sphere.center.x - this.origin.x;
  55281. var y = sphere.center.y - this.origin.y;
  55282. var z = sphere.center.z - this.origin.z;
  55283. var pyth = (x * x) + (y * y) + (z * z);
  55284. var rr = sphere.radius * sphere.radius;
  55285. if (pyth <= rr) {
  55286. return true;
  55287. }
  55288. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55289. if (dot < 0.0) {
  55290. return false;
  55291. }
  55292. var temp = pyth - (dot * dot);
  55293. return temp <= rr;
  55294. };
  55295. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55296. if (!this._edge1) {
  55297. this._edge1 = BABYLON.Vector3.Zero();
  55298. this._edge2 = BABYLON.Vector3.Zero();
  55299. this._pvec = BABYLON.Vector3.Zero();
  55300. this._tvec = BABYLON.Vector3.Zero();
  55301. this._qvec = BABYLON.Vector3.Zero();
  55302. }
  55303. vertex1.subtractToRef(vertex0, this._edge1);
  55304. vertex2.subtractToRef(vertex0, this._edge2);
  55305. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55306. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55307. if (det === 0) {
  55308. return null;
  55309. }
  55310. var invdet = 1 / det;
  55311. this.origin.subtractToRef(vertex0, this._tvec);
  55312. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55313. if (bu < 0 || bu > 1.0) {
  55314. return null;
  55315. }
  55316. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55317. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55318. if (bv < 0 || bu + bv > 1.0) {
  55319. return null;
  55320. }
  55321. //check if the distance is longer than the predefined length.
  55322. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55323. if (distance > this.length) {
  55324. return null;
  55325. }
  55326. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55327. };
  55328. Ray.prototype.intersectsPlane = function (plane) {
  55329. var distance;
  55330. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55331. if (Math.abs(result1) < 9.99999997475243E-07) {
  55332. return null;
  55333. }
  55334. else {
  55335. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55336. distance = (-plane.d - result2) / result1;
  55337. if (distance < 0.0) {
  55338. if (distance < -9.99999997475243E-07) {
  55339. return null;
  55340. }
  55341. else {
  55342. return 0;
  55343. }
  55344. }
  55345. return distance;
  55346. }
  55347. };
  55348. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55349. var tm = BABYLON.Tmp.Matrix[0];
  55350. mesh.getWorldMatrix().invertToRef(tm);
  55351. if (this._tmpRay) {
  55352. Ray.TransformToRef(this, tm, this._tmpRay);
  55353. }
  55354. else {
  55355. this._tmpRay = Ray.Transform(this, tm);
  55356. }
  55357. return mesh.intersects(this._tmpRay, fastCheck);
  55358. };
  55359. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55360. if (results) {
  55361. results.length = 0;
  55362. }
  55363. else {
  55364. results = [];
  55365. }
  55366. for (var i = 0; i < meshes.length; i++) {
  55367. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55368. if (pickInfo.hit) {
  55369. results.push(pickInfo);
  55370. }
  55371. }
  55372. results.sort(this._comparePickingInfo);
  55373. return results;
  55374. };
  55375. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55376. if (pickingInfoA.distance < pickingInfoB.distance) {
  55377. return -1;
  55378. }
  55379. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55380. return 1;
  55381. }
  55382. else {
  55383. return 0;
  55384. }
  55385. };
  55386. /**
  55387. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55388. * @param sega the first point of the segment to test the intersection against
  55389. * @param segb the second point of the segment to test the intersection against
  55390. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55391. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55392. */
  55393. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55394. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55395. var u = segb.subtract(sega);
  55396. var v = rsegb.subtract(this.origin);
  55397. var w = sega.subtract(this.origin);
  55398. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55399. var b = BABYLON.Vector3.Dot(u, v);
  55400. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55401. var d = BABYLON.Vector3.Dot(u, w);
  55402. var e = BABYLON.Vector3.Dot(v, w);
  55403. var D = a * c - b * b; // always >= 0
  55404. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55405. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55406. // compute the line parameters of the two closest points
  55407. if (D < Ray.smallnum) { // the lines are almost parallel
  55408. sN = 0.0; // force using point P0 on segment S1
  55409. sD = 1.0; // to prevent possible division by 0.0 later
  55410. tN = e;
  55411. tD = c;
  55412. }
  55413. else { // get the closest points on the infinite lines
  55414. sN = (b * e - c * d);
  55415. tN = (a * e - b * d);
  55416. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55417. sN = 0.0;
  55418. tN = e;
  55419. tD = c;
  55420. }
  55421. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55422. sN = sD;
  55423. tN = e + b;
  55424. tD = c;
  55425. }
  55426. }
  55427. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55428. tN = 0.0;
  55429. // recompute sc for this edge
  55430. if (-d < 0.0) {
  55431. sN = 0.0;
  55432. }
  55433. else if (-d > a)
  55434. sN = sD;
  55435. else {
  55436. sN = -d;
  55437. sD = a;
  55438. }
  55439. }
  55440. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55441. tN = tD;
  55442. // recompute sc for this edge
  55443. if ((-d + b) < 0.0) {
  55444. sN = 0;
  55445. }
  55446. else if ((-d + b) > a) {
  55447. sN = sD;
  55448. }
  55449. else {
  55450. sN = (-d + b);
  55451. sD = a;
  55452. }
  55453. }
  55454. // finally do the division to get sc and tc
  55455. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55456. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55457. // get the difference of the two closest points
  55458. var qtc = v.multiplyByFloats(tc, tc, tc);
  55459. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55460. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55461. if (isIntersected) {
  55462. return qtc.length();
  55463. }
  55464. return -1;
  55465. };
  55466. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55467. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55468. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55469. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55470. this.direction.normalize();
  55471. return this;
  55472. };
  55473. // Statics
  55474. Ray.Zero = function () {
  55475. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55476. };
  55477. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55478. var result = Ray.Zero();
  55479. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55480. };
  55481. /**
  55482. * 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
  55483. * transformed to the given world matrix.
  55484. * @param origin The origin point
  55485. * @param end The end point
  55486. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55487. */
  55488. Ray.CreateNewFromTo = function (origin, end, world) {
  55489. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55490. var direction = end.subtract(origin);
  55491. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55492. direction.normalize();
  55493. return Ray.Transform(new Ray(origin, direction, length), world);
  55494. };
  55495. Ray.Transform = function (ray, matrix) {
  55496. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55497. Ray.TransformToRef(ray, matrix, result);
  55498. return result;
  55499. };
  55500. Ray.TransformToRef = function (ray, matrix, result) {
  55501. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55502. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55503. result.length = ray.length;
  55504. var dir = result.direction;
  55505. var len = dir.length();
  55506. if (!(len === 0 || len === 1)) {
  55507. var num = 1.0 / len;
  55508. dir.x *= num;
  55509. dir.y *= num;
  55510. dir.z *= num;
  55511. result.length *= len;
  55512. }
  55513. };
  55514. Ray.smallnum = 0.00000001;
  55515. Ray.rayl = 10e8;
  55516. return Ray;
  55517. }());
  55518. BABYLON.Ray = Ray;
  55519. })(BABYLON || (BABYLON = {}));
  55520. //# sourceMappingURL=babylon.ray.js.map
  55521. var BABYLON;
  55522. (function (BABYLON) {
  55523. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55524. if (boxMin.x > sphereCenter.x + sphereRadius)
  55525. return false;
  55526. if (sphereCenter.x - sphereRadius > boxMax.x)
  55527. return false;
  55528. if (boxMin.y > sphereCenter.y + sphereRadius)
  55529. return false;
  55530. if (sphereCenter.y - sphereRadius > boxMax.y)
  55531. return false;
  55532. if (boxMin.z > sphereCenter.z + sphereRadius)
  55533. return false;
  55534. if (sphereCenter.z - sphereRadius > boxMax.z)
  55535. return false;
  55536. return true;
  55537. };
  55538. var getLowestRoot = (function () {
  55539. var result = { root: 0, found: false };
  55540. return function (a, b, c, maxR) {
  55541. result.root = 0;
  55542. result.found = false;
  55543. var determinant = b * b - 4.0 * a * c;
  55544. if (determinant < 0)
  55545. return result;
  55546. var sqrtD = Math.sqrt(determinant);
  55547. var r1 = (-b - sqrtD) / (2.0 * a);
  55548. var r2 = (-b + sqrtD) / (2.0 * a);
  55549. if (r1 > r2) {
  55550. var temp = r2;
  55551. r2 = r1;
  55552. r1 = temp;
  55553. }
  55554. if (r1 > 0 && r1 < maxR) {
  55555. result.root = r1;
  55556. result.found = true;
  55557. return result;
  55558. }
  55559. if (r2 > 0 && r2 < maxR) {
  55560. result.root = r2;
  55561. result.found = true;
  55562. return result;
  55563. }
  55564. return result;
  55565. };
  55566. })();
  55567. var Collider = /** @class */ (function () {
  55568. function Collider() {
  55569. this._collisionPoint = BABYLON.Vector3.Zero();
  55570. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55571. this._tempVector = BABYLON.Vector3.Zero();
  55572. this._tempVector2 = BABYLON.Vector3.Zero();
  55573. this._tempVector3 = BABYLON.Vector3.Zero();
  55574. this._tempVector4 = BABYLON.Vector3.Zero();
  55575. this._edge = BABYLON.Vector3.Zero();
  55576. this._baseToVertex = BABYLON.Vector3.Zero();
  55577. this._destinationPoint = BABYLON.Vector3.Zero();
  55578. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55579. this._displacementVector = BABYLON.Vector3.Zero();
  55580. this._radius = BABYLON.Vector3.One();
  55581. this._retry = 0;
  55582. this._basePointWorld = BABYLON.Vector3.Zero();
  55583. this._velocityWorld = BABYLON.Vector3.Zero();
  55584. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55585. this._collisionMask = -1;
  55586. }
  55587. Object.defineProperty(Collider.prototype, "collisionMask", {
  55588. get: function () {
  55589. return this._collisionMask;
  55590. },
  55591. set: function (mask) {
  55592. this._collisionMask = !isNaN(mask) ? mask : -1;
  55593. },
  55594. enumerable: true,
  55595. configurable: true
  55596. });
  55597. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55598. /**
  55599. * Gets the plane normal used to compute the sliding response (in local space)
  55600. */
  55601. get: function () {
  55602. return this._slidePlaneNormal;
  55603. },
  55604. enumerable: true,
  55605. configurable: true
  55606. });
  55607. // Methods
  55608. Collider.prototype._initialize = function (source, dir, e) {
  55609. this._velocity = dir;
  55610. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55611. this._basePoint = source;
  55612. source.multiplyToRef(this._radius, this._basePointWorld);
  55613. dir.multiplyToRef(this._radius, this._velocityWorld);
  55614. this._velocityWorldLength = this._velocityWorld.length();
  55615. this._epsilon = e;
  55616. this.collisionFound = false;
  55617. };
  55618. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55619. pa.subtractToRef(point, this._tempVector);
  55620. pb.subtractToRef(point, this._tempVector2);
  55621. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55622. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55623. if (d < 0)
  55624. return false;
  55625. pc.subtractToRef(point, this._tempVector3);
  55626. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55627. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55628. if (d < 0)
  55629. return false;
  55630. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55631. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55632. return d >= 0;
  55633. };
  55634. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55635. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55636. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55637. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55638. return false;
  55639. }
  55640. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55641. return false;
  55642. return true;
  55643. };
  55644. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55645. var t0;
  55646. var embeddedInPlane = false;
  55647. //defensive programming, actually not needed.
  55648. if (!trianglePlaneArray) {
  55649. trianglePlaneArray = [];
  55650. }
  55651. if (!trianglePlaneArray[faceIndex]) {
  55652. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55653. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55654. }
  55655. var trianglePlane = trianglePlaneArray[faceIndex];
  55656. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55657. return;
  55658. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55659. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55660. if (normalDotVelocity == 0) {
  55661. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55662. return;
  55663. embeddedInPlane = true;
  55664. t0 = 0;
  55665. }
  55666. else {
  55667. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55668. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55669. if (t0 > t1) {
  55670. var temp = t1;
  55671. t1 = t0;
  55672. t0 = temp;
  55673. }
  55674. if (t0 > 1.0 || t1 < 0.0)
  55675. return;
  55676. if (t0 < 0)
  55677. t0 = 0;
  55678. if (t0 > 1.0)
  55679. t0 = 1.0;
  55680. }
  55681. this._collisionPoint.copyFromFloats(0, 0, 0);
  55682. var found = false;
  55683. var t = 1.0;
  55684. if (!embeddedInPlane) {
  55685. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55686. this._velocity.scaleToRef(t0, this._tempVector);
  55687. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55688. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55689. found = true;
  55690. t = t0;
  55691. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55692. }
  55693. }
  55694. if (!found) {
  55695. var velocitySquaredLength = this._velocity.lengthSquared();
  55696. var a = velocitySquaredLength;
  55697. this._basePoint.subtractToRef(p1, this._tempVector);
  55698. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55699. var c = this._tempVector.lengthSquared() - 1.0;
  55700. var lowestRoot = getLowestRoot(a, b, c, t);
  55701. if (lowestRoot.found) {
  55702. t = lowestRoot.root;
  55703. found = true;
  55704. this._collisionPoint.copyFrom(p1);
  55705. }
  55706. this._basePoint.subtractToRef(p2, this._tempVector);
  55707. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55708. c = this._tempVector.lengthSquared() - 1.0;
  55709. lowestRoot = getLowestRoot(a, b, c, t);
  55710. if (lowestRoot.found) {
  55711. t = lowestRoot.root;
  55712. found = true;
  55713. this._collisionPoint.copyFrom(p2);
  55714. }
  55715. this._basePoint.subtractToRef(p3, this._tempVector);
  55716. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55717. c = this._tempVector.lengthSquared() - 1.0;
  55718. lowestRoot = getLowestRoot(a, b, c, t);
  55719. if (lowestRoot.found) {
  55720. t = lowestRoot.root;
  55721. found = true;
  55722. this._collisionPoint.copyFrom(p3);
  55723. }
  55724. p2.subtractToRef(p1, this._edge);
  55725. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55726. var edgeSquaredLength = this._edge.lengthSquared();
  55727. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55728. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55729. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55730. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55731. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55732. lowestRoot = getLowestRoot(a, b, c, t);
  55733. if (lowestRoot.found) {
  55734. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55735. if (f >= 0.0 && f <= 1.0) {
  55736. t = lowestRoot.root;
  55737. found = true;
  55738. this._edge.scaleInPlace(f);
  55739. p1.addToRef(this._edge, this._collisionPoint);
  55740. }
  55741. }
  55742. p3.subtractToRef(p2, this._edge);
  55743. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55744. edgeSquaredLength = this._edge.lengthSquared();
  55745. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55746. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55747. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55748. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55749. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55750. lowestRoot = getLowestRoot(a, b, c, t);
  55751. if (lowestRoot.found) {
  55752. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55753. if (f >= 0.0 && f <= 1.0) {
  55754. t = lowestRoot.root;
  55755. found = true;
  55756. this._edge.scaleInPlace(f);
  55757. p2.addToRef(this._edge, this._collisionPoint);
  55758. }
  55759. }
  55760. p1.subtractToRef(p3, this._edge);
  55761. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55762. edgeSquaredLength = this._edge.lengthSquared();
  55763. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55764. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55765. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55766. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55767. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55768. lowestRoot = getLowestRoot(a, b, c, t);
  55769. if (lowestRoot.found) {
  55770. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55771. if (f >= 0.0 && f <= 1.0) {
  55772. t = lowestRoot.root;
  55773. found = true;
  55774. this._edge.scaleInPlace(f);
  55775. p3.addToRef(this._edge, this._collisionPoint);
  55776. }
  55777. }
  55778. }
  55779. if (found) {
  55780. var distToCollision = t * this._velocity.length();
  55781. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55782. if (!this.intersectionPoint) {
  55783. this.intersectionPoint = this._collisionPoint.clone();
  55784. }
  55785. else {
  55786. this.intersectionPoint.copyFrom(this._collisionPoint);
  55787. }
  55788. this._nearestDistance = distToCollision;
  55789. this.collisionFound = true;
  55790. }
  55791. }
  55792. };
  55793. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55794. for (var i = indexStart; i < indexEnd; i += 3) {
  55795. var p1 = pts[indices[i] - decal];
  55796. var p2 = pts[indices[i + 1] - decal];
  55797. var p3 = pts[indices[i + 2] - decal];
  55798. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55799. }
  55800. };
  55801. Collider.prototype._getResponse = function (pos, vel) {
  55802. pos.addToRef(vel, this._destinationPoint);
  55803. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55804. this._basePoint.addToRef(vel, pos);
  55805. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55806. this._slidePlaneNormal.normalize();
  55807. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55808. pos.addInPlace(this._displacementVector);
  55809. this.intersectionPoint.addInPlace(this._displacementVector);
  55810. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55811. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55812. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55813. };
  55814. return Collider;
  55815. }());
  55816. BABYLON.Collider = Collider;
  55817. })(BABYLON || (BABYLON = {}));
  55818. //# sourceMappingURL=babylon.collider.js.map
  55819. var BABYLON;
  55820. (function (BABYLON) {
  55821. //WebWorker code will be inserted to this variable.
  55822. BABYLON.CollisionWorker = "";
  55823. /** Defines supported task for worker process */
  55824. var WorkerTaskType;
  55825. (function (WorkerTaskType) {
  55826. /** Initialization */
  55827. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55828. /** Update of geometry */
  55829. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55830. /** Evaluate collision */
  55831. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55832. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55833. /** Defines kind of replies returned by worker */
  55834. var WorkerReplyType;
  55835. (function (WorkerReplyType) {
  55836. /** Success */
  55837. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55838. /** Unkown error */
  55839. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55840. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55841. var CollisionCoordinatorWorker = /** @class */ (function () {
  55842. function CollisionCoordinatorWorker() {
  55843. var _this = this;
  55844. this._scaledPosition = BABYLON.Vector3.Zero();
  55845. this._scaledVelocity = BABYLON.Vector3.Zero();
  55846. this.onMeshUpdated = function (transformNode) {
  55847. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55848. };
  55849. this.onGeometryUpdated = function (geometry) {
  55850. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55851. };
  55852. this._afterRender = function () {
  55853. if (!_this._init)
  55854. return;
  55855. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55856. return;
  55857. }
  55858. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55859. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55860. if (_this._runningUpdated > 4) {
  55861. return;
  55862. }
  55863. ++_this._runningUpdated;
  55864. var payload = {
  55865. updatedMeshes: _this._addUpdateMeshesList,
  55866. updatedGeometries: _this._addUpdateGeometriesList,
  55867. removedGeometries: _this._toRemoveGeometryArray,
  55868. removedMeshes: _this._toRemoveMeshesArray
  55869. };
  55870. var message = {
  55871. payload: payload,
  55872. taskType: WorkerTaskType.UPDATE
  55873. };
  55874. var serializable = [];
  55875. for (var id in payload.updatedGeometries) {
  55876. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55877. //prepare transferables
  55878. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55879. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55880. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55881. }
  55882. }
  55883. _this._worker.postMessage(message, serializable);
  55884. _this._addUpdateMeshesList = {};
  55885. _this._addUpdateGeometriesList = {};
  55886. _this._toRemoveGeometryArray = [];
  55887. _this._toRemoveMeshesArray = [];
  55888. };
  55889. this._onMessageFromWorker = function (e) {
  55890. var returnData = e.data;
  55891. if (returnData.error != WorkerReplyType.SUCCESS) {
  55892. //TODO what errors can be returned from the worker?
  55893. BABYLON.Tools.Warn("error returned from worker!");
  55894. return;
  55895. }
  55896. switch (returnData.taskType) {
  55897. case WorkerTaskType.INIT:
  55898. _this._init = true;
  55899. //Update the worked with ALL of the scene's current state
  55900. _this._scene.meshes.forEach(function (mesh) {
  55901. _this.onMeshAdded(mesh);
  55902. });
  55903. _this._scene.getGeometries().forEach(function (geometry) {
  55904. _this.onGeometryAdded(geometry);
  55905. });
  55906. break;
  55907. case WorkerTaskType.UPDATE:
  55908. _this._runningUpdated--;
  55909. break;
  55910. case WorkerTaskType.COLLIDE:
  55911. var returnPayload = returnData.payload;
  55912. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55913. return;
  55914. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55915. if (callback) {
  55916. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55917. if (mesh) {
  55918. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55919. }
  55920. }
  55921. //cleanup
  55922. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55923. break;
  55924. }
  55925. };
  55926. this._collisionsCallbackArray = [];
  55927. this._init = false;
  55928. this._runningUpdated = 0;
  55929. this._addUpdateMeshesList = {};
  55930. this._addUpdateGeometriesList = {};
  55931. this._toRemoveGeometryArray = [];
  55932. this._toRemoveMeshesArray = [];
  55933. }
  55934. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55935. if (!this._init)
  55936. return;
  55937. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55938. return;
  55939. position.divideToRef(collider._radius, this._scaledPosition);
  55940. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55941. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55942. var payload = {
  55943. collider: {
  55944. position: this._scaledPosition.asArray(),
  55945. velocity: this._scaledVelocity.asArray(),
  55946. radius: collider._radius.asArray()
  55947. },
  55948. collisionId: collisionIndex,
  55949. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55950. maximumRetry: maximumRetry
  55951. };
  55952. var message = {
  55953. payload: payload,
  55954. taskType: WorkerTaskType.COLLIDE
  55955. };
  55956. this._worker.postMessage(message);
  55957. };
  55958. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55959. this._scene = scene;
  55960. this._scene.registerAfterRender(this._afterRender);
  55961. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55962. this._worker = new Worker(workerUrl);
  55963. this._worker.onmessage = this._onMessageFromWorker;
  55964. var message = {
  55965. payload: {},
  55966. taskType: WorkerTaskType.INIT
  55967. };
  55968. this._worker.postMessage(message);
  55969. };
  55970. CollisionCoordinatorWorker.prototype.destroy = function () {
  55971. this._scene.unregisterAfterRender(this._afterRender);
  55972. this._worker.terminate();
  55973. };
  55974. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55975. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55976. this.onMeshUpdated(mesh);
  55977. };
  55978. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55979. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55980. };
  55981. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55982. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55983. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55984. this.onGeometryUpdated(geometry);
  55985. };
  55986. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55987. this._toRemoveGeometryArray.push(geometry.id);
  55988. };
  55989. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55990. var submeshes = [];
  55991. if (mesh.subMeshes) {
  55992. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55993. var boundingInfo = sm.getBoundingInfo();
  55994. return {
  55995. position: idx,
  55996. verticesStart: sm.verticesStart,
  55997. verticesCount: sm.verticesCount,
  55998. indexStart: sm.indexStart,
  55999. indexCount: sm.indexCount,
  56000. hasMaterial: !!sm.getMaterial(),
  56001. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56002. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56003. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56004. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56005. };
  56006. });
  56007. }
  56008. var geometryId = null;
  56009. if (mesh instanceof BABYLON.Mesh) {
  56010. var geometry = mesh.geometry;
  56011. geometryId = geometry ? geometry.id : null;
  56012. }
  56013. else if (mesh instanceof BABYLON.InstancedMesh) {
  56014. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56015. geometryId = geometry ? geometry.id : null;
  56016. }
  56017. var boundingInfo = mesh.getBoundingInfo();
  56018. return {
  56019. uniqueId: mesh.uniqueId,
  56020. id: mesh.id,
  56021. name: mesh.name,
  56022. geometryId: geometryId,
  56023. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56024. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56025. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56026. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56027. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56028. subMeshes: submeshes,
  56029. checkCollisions: mesh.checkCollisions
  56030. };
  56031. };
  56032. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56033. return {
  56034. id: geometry.id,
  56035. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56036. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56037. indices: new Uint32Array(geometry.getIndices() || []),
  56038. };
  56039. };
  56040. return CollisionCoordinatorWorker;
  56041. }());
  56042. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56043. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56044. function CollisionCoordinatorLegacy() {
  56045. this._scaledPosition = BABYLON.Vector3.Zero();
  56046. this._scaledVelocity = BABYLON.Vector3.Zero();
  56047. this._finalPosition = BABYLON.Vector3.Zero();
  56048. }
  56049. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56050. position.divideToRef(collider._radius, this._scaledPosition);
  56051. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56052. collider.collidedMesh = null;
  56053. collider._retry = 0;
  56054. collider._initialVelocity = this._scaledVelocity;
  56055. collider._initialPosition = this._scaledPosition;
  56056. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56057. this._finalPosition.multiplyInPlace(collider._radius);
  56058. //run the callback
  56059. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56060. };
  56061. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56062. this._scene = scene;
  56063. };
  56064. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56065. //Legacy need no destruction method.
  56066. };
  56067. //No update in legacy mode
  56068. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56069. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56070. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56071. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56072. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56073. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56074. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56075. if (excludedMesh === void 0) { excludedMesh = null; }
  56076. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56077. if (collider._retry >= maximumRetry) {
  56078. finalPosition.copyFrom(position);
  56079. return;
  56080. }
  56081. // Check if this is a mesh else camera or -1
  56082. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56083. collider._initialize(position, velocity, closeDistance);
  56084. // Check all meshes
  56085. for (var index = 0; index < this._scene.meshes.length; index++) {
  56086. var mesh = this._scene.meshes[index];
  56087. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56088. mesh._checkCollision(collider);
  56089. }
  56090. }
  56091. if (!collider.collisionFound) {
  56092. position.addToRef(velocity, finalPosition);
  56093. return;
  56094. }
  56095. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56096. collider._getResponse(position, velocity);
  56097. }
  56098. if (velocity.length() <= closeDistance) {
  56099. finalPosition.copyFrom(position);
  56100. return;
  56101. }
  56102. collider._retry++;
  56103. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56104. };
  56105. return CollisionCoordinatorLegacy;
  56106. }());
  56107. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56108. })(BABYLON || (BABYLON = {}));
  56109. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56110. var BABYLON;
  56111. (function (BABYLON) {
  56112. /**
  56113. * A particle represents one of the element emitted by a particle system.
  56114. * This is mainly define by its coordinates, direction, velocity and age.
  56115. */
  56116. var Particle = /** @class */ (function () {
  56117. /**
  56118. * Creates a new instance Particle
  56119. * @param particleSystem the particle system the particle belongs to
  56120. */
  56121. function Particle(
  56122. /**
  56123. * particleSystem the particle system the particle belongs to.
  56124. */
  56125. particleSystem) {
  56126. this.particleSystem = particleSystem;
  56127. /**
  56128. * The world position of the particle in the scene.
  56129. */
  56130. this.position = BABYLON.Vector3.Zero();
  56131. /**
  56132. * The world direction of the particle in the scene.
  56133. */
  56134. this.direction = BABYLON.Vector3.Zero();
  56135. /**
  56136. * The color of the particle.
  56137. */
  56138. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56139. /**
  56140. * The color change of the particle per step.
  56141. */
  56142. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56143. /**
  56144. * Defines how long will the life of the particle be.
  56145. */
  56146. this.lifeTime = 1.0;
  56147. /**
  56148. * The current age of the particle.
  56149. */
  56150. this.age = 0;
  56151. /**
  56152. * The current size of the particle.
  56153. */
  56154. this.size = 0;
  56155. /**
  56156. * The current scale of the particle.
  56157. */
  56158. this.scale = new BABYLON.Vector2(1, 1);
  56159. /**
  56160. * The current angle of the particle.
  56161. */
  56162. this.angle = 0;
  56163. /**
  56164. * Defines how fast is the angle changing.
  56165. */
  56166. this.angularSpeed = 0;
  56167. /**
  56168. * Defines the cell index used by the particle to be rendered from a sprite.
  56169. */
  56170. this.cellIndex = 0;
  56171. this._currentFrameCounter = 0;
  56172. if (!this.particleSystem.isAnimationSheetEnabled) {
  56173. return;
  56174. }
  56175. this.updateCellInfoFromSystem();
  56176. }
  56177. Particle.prototype.updateCellInfoFromSystem = function () {
  56178. this.cellIndex = this.particleSystem.startSpriteCellID;
  56179. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  56180. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  56181. }
  56182. else {
  56183. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56184. }
  56185. };
  56186. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56187. // (ageOffset / scaledUpdateSpeed) / available cells
  56188. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56189. this._currentFrameCounter += scaledUpdateSpeed;
  56190. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56191. this._currentFrameCounter = 0;
  56192. this.cellIndex++;
  56193. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56194. this.cellIndex = this.particleSystem.endSpriteCellID;
  56195. }
  56196. }
  56197. };
  56198. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56199. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56200. this.cellIndex++;
  56201. this._currentFrameCounter = 0;
  56202. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56203. if (this.particleSystem.spriteCellLoop) {
  56204. this.cellIndex = this.particleSystem.startSpriteCellID;
  56205. }
  56206. else {
  56207. this.cellIndex = this.particleSystem.endSpriteCellID;
  56208. }
  56209. }
  56210. }
  56211. else {
  56212. this._currentFrameCounter++;
  56213. }
  56214. };
  56215. /**
  56216. * Copy the properties of particle to another one.
  56217. * @param other the particle to copy the information to.
  56218. */
  56219. Particle.prototype.copyTo = function (other) {
  56220. other.position.copyFrom(this.position);
  56221. other.direction.copyFrom(this.direction);
  56222. other.color.copyFrom(this.color);
  56223. other.colorStep.copyFrom(this.colorStep);
  56224. other.lifeTime = this.lifeTime;
  56225. other.age = this.age;
  56226. other.size = this.size;
  56227. other.scale.copyFrom(this.scale);
  56228. other.angle = this.angle;
  56229. other.angularSpeed = this.angularSpeed;
  56230. other.particleSystem = this.particleSystem;
  56231. other.cellIndex = this.cellIndex;
  56232. };
  56233. return Particle;
  56234. }());
  56235. BABYLON.Particle = Particle;
  56236. })(BABYLON || (BABYLON = {}));
  56237. //# sourceMappingURL=babylon.particle.js.map
  56238. var BABYLON;
  56239. (function (BABYLON) {
  56240. /**
  56241. * This represents a particle system in Babylon.
  56242. * 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.
  56243. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56244. * @example https://doc.babylonjs.com/babylon101/particles
  56245. */
  56246. var ParticleSystem = /** @class */ (function () {
  56247. /**
  56248. * Instantiates a particle system.
  56249. * 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.
  56250. * @param name The name of the particle system
  56251. * @param capacity The max number of particles alive at the same time
  56252. * @param scene The scene the particle system belongs to
  56253. * @param customEffect a custom effect used to change the way particles are rendered by default
  56254. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56255. * @param epsilon Offset used to render the particles
  56256. */
  56257. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56258. if (customEffect === void 0) { customEffect = null; }
  56259. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56260. if (epsilon === void 0) { epsilon = 0.01; }
  56261. var _this = this;
  56262. /**
  56263. * List of animations used by the particle system.
  56264. */
  56265. this.animations = [];
  56266. /**
  56267. * The rendering group used by the Particle system to chose when to render.
  56268. */
  56269. this.renderingGroupId = 0;
  56270. /**
  56271. * The emitter represents the Mesh or position we are attaching the particle system to.
  56272. */
  56273. this.emitter = null;
  56274. /**
  56275. * The maximum number of particles to emit per frame
  56276. */
  56277. this.emitRate = 10;
  56278. /**
  56279. * If you want to launch only a few particles at once, that can be done, as well.
  56280. */
  56281. this.manualEmitCount = -1;
  56282. /**
  56283. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56284. */
  56285. this.updateSpeed = 0.01;
  56286. /**
  56287. * The amount of time the particle system is running (depends of the overall update speed).
  56288. */
  56289. this.targetStopDuration = 0;
  56290. /**
  56291. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56292. */
  56293. this.disposeOnStop = false;
  56294. /**
  56295. * Minimum power of emitting particles.
  56296. */
  56297. this.minEmitPower = 1;
  56298. /**
  56299. * Maximum power of emitting particles.
  56300. */
  56301. this.maxEmitPower = 1;
  56302. /**
  56303. * Minimum life time of emitting particles.
  56304. */
  56305. this.minLifeTime = 1;
  56306. /**
  56307. * Maximum life time of emitting particles.
  56308. */
  56309. this.maxLifeTime = 1;
  56310. /**
  56311. * Minimum Size of emitting particles.
  56312. */
  56313. this.minSize = 1;
  56314. /**
  56315. * Maximum Size of emitting particles.
  56316. */
  56317. this.maxSize = 1;
  56318. /**
  56319. * Minimum scale of emitting particles on X axis.
  56320. */
  56321. this.minScaleX = 1;
  56322. /**
  56323. * Maximum scale of emitting particles on X axis.
  56324. */
  56325. this.maxScaleX = 1;
  56326. /**
  56327. * Minimum scale of emitting particles on Y axis.
  56328. */
  56329. this.minScaleY = 1;
  56330. /**
  56331. * Maximum scale of emitting particles on Y axis.
  56332. */
  56333. this.maxScaleY = 1;
  56334. /**
  56335. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56336. */
  56337. this.minAngularSpeed = 0;
  56338. /**
  56339. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56340. */
  56341. this.maxAngularSpeed = 0;
  56342. /**
  56343. * The layer mask we are rendering the particles through.
  56344. */
  56345. this.layerMask = 0x0FFFFFFF;
  56346. /**
  56347. * This can help using your own shader to render the particle system.
  56348. * The according effect will be created
  56349. */
  56350. this.customShader = null;
  56351. /**
  56352. * By default particle system starts as soon as they are created. This prevents the
  56353. * automatic start to happen and let you decide when to start emitting particles.
  56354. */
  56355. this.preventAutoStart = false;
  56356. /**
  56357. * Callback triggered when the particle animation is ending.
  56358. */
  56359. this.onAnimationEnd = null;
  56360. /**
  56361. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56362. */
  56363. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56364. /**
  56365. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56366. * to override the particles.
  56367. */
  56368. this.forceDepthWrite = false;
  56369. /**
  56370. * You can use gravity if you want to give an orientation to your particles.
  56371. */
  56372. this.gravity = BABYLON.Vector3.Zero();
  56373. /**
  56374. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56375. */
  56376. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56377. /**
  56378. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56379. */
  56380. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56381. /**
  56382. * Color the particle will have at the end of its lifetime.
  56383. */
  56384. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56385. /**
  56386. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56387. */
  56388. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56389. /**
  56390. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56391. */
  56392. this.spriteCellLoop = true;
  56393. /**
  56394. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56395. */
  56396. this.spriteCellChangeSpeed = 0;
  56397. /**
  56398. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56399. */
  56400. this.startSpriteCellID = 0;
  56401. /**
  56402. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56403. */
  56404. this.endSpriteCellID = 0;
  56405. /**
  56406. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56407. */
  56408. this.spriteCellWidth = 0;
  56409. /**
  56410. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56411. */
  56412. this.spriteCellHeight = 0;
  56413. /**
  56414. * An event triggered when the system is disposed.
  56415. */
  56416. this.onDisposeObservable = new BABYLON.Observable();
  56417. this._particles = new Array();
  56418. this._stockParticles = new Array();
  56419. this._newPartsExcess = 0;
  56420. this._vertexBuffers = {};
  56421. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56422. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56423. this._scaledDirection = BABYLON.Vector3.Zero();
  56424. this._scaledGravity = BABYLON.Vector3.Zero();
  56425. this._currentRenderId = -1;
  56426. this._started = false;
  56427. this._stopped = false;
  56428. this._actualFrame = 0;
  56429. this._vertexBufferSize = 12;
  56430. // start of sub system methods
  56431. /**
  56432. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56433. * Its lifetime will start back at 0.
  56434. */
  56435. this.recycleParticle = function (particle) {
  56436. var lastParticle = _this._particles.pop();
  56437. if (lastParticle !== particle) {
  56438. lastParticle.copyTo(particle);
  56439. }
  56440. _this._stockParticles.push(lastParticle);
  56441. };
  56442. this._createParticle = function () {
  56443. var particle;
  56444. if (_this._stockParticles.length !== 0) {
  56445. particle = _this._stockParticles.pop();
  56446. particle.age = 0;
  56447. particle.cellIndex = _this.startSpriteCellID;
  56448. }
  56449. else {
  56450. particle = new BABYLON.Particle(_this);
  56451. }
  56452. return particle;
  56453. };
  56454. this._emitFromParticle = function (particle) {
  56455. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56456. return;
  56457. }
  56458. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56459. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56460. subSystem._rootParticleSystem = _this;
  56461. _this.activeSubSystems.push(subSystem);
  56462. subSystem.start();
  56463. };
  56464. this._appendParticleVertexes = null;
  56465. this.id = name;
  56466. this.name = name;
  56467. this._capacity = capacity;
  56468. this._epsilon = epsilon;
  56469. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56470. if (isAnimationSheetEnabled) {
  56471. this._vertexBufferSize = 13;
  56472. }
  56473. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56474. this._customEffect = customEffect;
  56475. scene.particleSystems.push(this);
  56476. this._createIndexBuffer();
  56477. // 13 floats per particle (x, y, z, r, g, b, a, angle, scaleX, scaleY, offsetX, offsetY) + 1 filler
  56478. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56479. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56480. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56481. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56482. var options = this._vertexBuffer.createVertexBuffer("options", 7, 3);
  56483. var size = this._vertexBuffer.createVertexBuffer("size", 10, 2);
  56484. if (this._isAnimationSheetEnabled) {
  56485. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 12, 1);
  56486. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56487. }
  56488. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56489. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56490. this._vertexBuffers["options"] = options;
  56491. this._vertexBuffers["size"] = size;
  56492. // Default emitter type
  56493. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56494. this.updateFunction = function (particles) {
  56495. for (var index = 0; index < particles.length; index++) {
  56496. var particle = particles[index];
  56497. particle.age += _this._scaledUpdateSpeed;
  56498. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56499. _this._emitFromParticle(particle);
  56500. _this.recycleParticle(particle);
  56501. index--;
  56502. continue;
  56503. }
  56504. else {
  56505. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56506. particle.color.addInPlace(_this._scaledColorStep);
  56507. if (particle.color.a < 0)
  56508. particle.color.a = 0;
  56509. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56510. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56511. particle.position.addInPlace(_this._scaledDirection);
  56512. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56513. particle.direction.addInPlace(_this._scaledGravity);
  56514. if (_this._isAnimationSheetEnabled) {
  56515. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56516. }
  56517. }
  56518. }
  56519. };
  56520. }
  56521. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56522. /**
  56523. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56524. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56525. */
  56526. get: function () {
  56527. if (this.particleEmitterType.direction1) {
  56528. return this.particleEmitterType.direction1;
  56529. }
  56530. return BABYLON.Vector3.Zero();
  56531. },
  56532. set: function (value) {
  56533. if (this.particleEmitterType.direction1) {
  56534. this.particleEmitterType.direction1 = value;
  56535. }
  56536. },
  56537. enumerable: true,
  56538. configurable: true
  56539. });
  56540. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56541. /**
  56542. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56543. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56544. */
  56545. get: function () {
  56546. if (this.particleEmitterType.direction2) {
  56547. return this.particleEmitterType.direction2;
  56548. }
  56549. return BABYLON.Vector3.Zero();
  56550. },
  56551. set: function (value) {
  56552. if (this.particleEmitterType.direction2) {
  56553. this.particleEmitterType.direction2 = value;
  56554. }
  56555. },
  56556. enumerable: true,
  56557. configurable: true
  56558. });
  56559. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56560. /**
  56561. * 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.
  56562. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56563. */
  56564. get: function () {
  56565. if (this.particleEmitterType.minEmitBox) {
  56566. return this.particleEmitterType.minEmitBox;
  56567. }
  56568. return BABYLON.Vector3.Zero();
  56569. },
  56570. set: function (value) {
  56571. if (this.particleEmitterType.minEmitBox) {
  56572. this.particleEmitterType.minEmitBox = value;
  56573. }
  56574. },
  56575. enumerable: true,
  56576. configurable: true
  56577. });
  56578. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56579. /**
  56580. * 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.
  56581. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56582. */
  56583. get: function () {
  56584. if (this.particleEmitterType.maxEmitBox) {
  56585. return this.particleEmitterType.maxEmitBox;
  56586. }
  56587. return BABYLON.Vector3.Zero();
  56588. },
  56589. set: function (value) {
  56590. if (this.particleEmitterType.maxEmitBox) {
  56591. this.particleEmitterType.maxEmitBox = value;
  56592. }
  56593. },
  56594. enumerable: true,
  56595. configurable: true
  56596. });
  56597. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56598. /**
  56599. * Sets a callback that will be triggered when the system is disposed.
  56600. */
  56601. set: function (callback) {
  56602. if (this._onDisposeObserver) {
  56603. this.onDisposeObservable.remove(this._onDisposeObserver);
  56604. }
  56605. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56606. },
  56607. enumerable: true,
  56608. configurable: true
  56609. });
  56610. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56611. /**
  56612. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56613. */
  56614. get: function () {
  56615. return this._isAnimationSheetEnabled;
  56616. },
  56617. enumerable: true,
  56618. configurable: true
  56619. });
  56620. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56621. //end of Sub-emitter
  56622. /**
  56623. * Gets the current list of active particles
  56624. */
  56625. get: function () {
  56626. return this._particles;
  56627. },
  56628. enumerable: true,
  56629. configurable: true
  56630. });
  56631. /**
  56632. * Returns the string "ParticleSystem"
  56633. * @returns a string containing the class name
  56634. */
  56635. ParticleSystem.prototype.getClassName = function () {
  56636. return "ParticleSystem";
  56637. };
  56638. ParticleSystem.prototype._createIndexBuffer = function () {
  56639. var indices = [];
  56640. var index = 0;
  56641. for (var count = 0; count < this._capacity; count++) {
  56642. indices.push(index);
  56643. indices.push(index + 1);
  56644. indices.push(index + 2);
  56645. indices.push(index);
  56646. indices.push(index + 2);
  56647. indices.push(index + 3);
  56648. index += 4;
  56649. }
  56650. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56651. };
  56652. /**
  56653. * Gets the maximum number of particles active at the same time.
  56654. * @returns The max number of active particles.
  56655. */
  56656. ParticleSystem.prototype.getCapacity = function () {
  56657. return this._capacity;
  56658. };
  56659. /**
  56660. * Gets Wether there are still active particles in the system.
  56661. * @returns True if it is alive, otherwise false.
  56662. */
  56663. ParticleSystem.prototype.isAlive = function () {
  56664. return this._alive;
  56665. };
  56666. /**
  56667. * Gets Wether the system has been started.
  56668. * @returns True if it has been started, otherwise false.
  56669. */
  56670. ParticleSystem.prototype.isStarted = function () {
  56671. return this._started;
  56672. };
  56673. /**
  56674. * Starts the particle system and begins to emit.
  56675. */
  56676. ParticleSystem.prototype.start = function () {
  56677. this._started = true;
  56678. this._stopped = false;
  56679. this._actualFrame = 0;
  56680. if (this.subEmitters && this.subEmitters.length != 0) {
  56681. this.activeSubSystems = new Array();
  56682. }
  56683. };
  56684. /**
  56685. * Stops the particle system.
  56686. * @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.
  56687. */
  56688. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56689. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56690. this._stopped = true;
  56691. if (stopSubEmitters) {
  56692. this._stopSubEmitters();
  56693. }
  56694. };
  56695. // animation sheet
  56696. /**
  56697. * Remove all active particles
  56698. */
  56699. ParticleSystem.prototype.reset = function () {
  56700. this._stockParticles = [];
  56701. this._particles = [];
  56702. };
  56703. /**
  56704. * @hidden (for internal use only)
  56705. */
  56706. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56707. var offset = index * this._vertexBufferSize;
  56708. this._vertexData[offset] = particle.position.x;
  56709. this._vertexData[offset + 1] = particle.position.y;
  56710. this._vertexData[offset + 2] = particle.position.z;
  56711. this._vertexData[offset + 3] = particle.color.r;
  56712. this._vertexData[offset + 4] = particle.color.g;
  56713. this._vertexData[offset + 5] = particle.color.b;
  56714. this._vertexData[offset + 6] = particle.color.a;
  56715. this._vertexData[offset + 7] = particle.angle;
  56716. this._vertexData[offset + 8] = offsetX;
  56717. this._vertexData[offset + 9] = offsetY;
  56718. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  56719. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  56720. };
  56721. /**
  56722. * @hidden (for internal use only)
  56723. */
  56724. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56725. if (offsetX === 0)
  56726. offsetX = this._epsilon;
  56727. else if (offsetX === 1)
  56728. offsetX = 1 - this._epsilon;
  56729. if (offsetY === 0)
  56730. offsetY = this._epsilon;
  56731. else if (offsetY === 1)
  56732. offsetY = 1 - this._epsilon;
  56733. var offset = index * this._vertexBufferSize;
  56734. this._vertexData[offset] = particle.position.x;
  56735. this._vertexData[offset + 1] = particle.position.y;
  56736. this._vertexData[offset + 2] = particle.position.z;
  56737. this._vertexData[offset + 3] = particle.color.r;
  56738. this._vertexData[offset + 4] = particle.color.g;
  56739. this._vertexData[offset + 5] = particle.color.b;
  56740. this._vertexData[offset + 6] = particle.color.a;
  56741. this._vertexData[offset + 7] = particle.angle;
  56742. this._vertexData[offset + 8] = offsetX;
  56743. this._vertexData[offset + 9] = offsetY;
  56744. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  56745. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  56746. this._vertexData[offset + 12] = particle.cellIndex;
  56747. };
  56748. ParticleSystem.prototype._stopSubEmitters = function () {
  56749. if (!this.activeSubSystems) {
  56750. return;
  56751. }
  56752. this.activeSubSystems.forEach(function (subSystem) {
  56753. subSystem.stop(true);
  56754. });
  56755. this.activeSubSystems = new Array();
  56756. };
  56757. ParticleSystem.prototype._removeFromRoot = function () {
  56758. if (!this._rootParticleSystem) {
  56759. return;
  56760. }
  56761. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56762. if (index !== -1) {
  56763. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56764. }
  56765. };
  56766. // end of sub system methods
  56767. ParticleSystem.prototype._update = function (newParticles) {
  56768. // Update current
  56769. this._alive = this._particles.length > 0;
  56770. this.updateFunction(this._particles);
  56771. // Add new ones
  56772. var worldMatrix;
  56773. if (this.emitter.position) {
  56774. var emitterMesh = this.emitter;
  56775. worldMatrix = emitterMesh.getWorldMatrix();
  56776. }
  56777. else {
  56778. var emitterPosition = this.emitter;
  56779. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56780. }
  56781. var particle;
  56782. for (var index = 0; index < newParticles; index++) {
  56783. if (this._particles.length === this._capacity) {
  56784. break;
  56785. }
  56786. particle = this._createParticle();
  56787. this._particles.push(particle);
  56788. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56789. if (this.startPositionFunction) {
  56790. this.startPositionFunction(worldMatrix, particle.position, particle);
  56791. }
  56792. else {
  56793. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56794. }
  56795. if (this.startDirectionFunction) {
  56796. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56797. }
  56798. else {
  56799. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56800. }
  56801. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56802. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56803. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  56804. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56805. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56806. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56807. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56808. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56809. }
  56810. };
  56811. ParticleSystem.prototype._getEffect = function () {
  56812. if (this._customEffect) {
  56813. return this._customEffect;
  56814. }
  56815. ;
  56816. var defines = [];
  56817. if (this._scene.clipPlane) {
  56818. defines.push("#define CLIPPLANE");
  56819. }
  56820. if (this._isAnimationSheetEnabled) {
  56821. defines.push("#define ANIMATESHEET");
  56822. }
  56823. // Effect
  56824. var join = defines.join("\n");
  56825. if (this._cachedDefines !== join) {
  56826. this._cachedDefines = join;
  56827. var attributesNamesOrOptions;
  56828. var effectCreationOption;
  56829. if (this._isAnimationSheetEnabled) {
  56830. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size", "cellIndex"];
  56831. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56832. }
  56833. else {
  56834. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size",];
  56835. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56836. }
  56837. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56838. }
  56839. return this._effect;
  56840. };
  56841. /**
  56842. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56843. */
  56844. ParticleSystem.prototype.animate = function () {
  56845. if (!this._started)
  56846. return;
  56847. var effect = this._getEffect();
  56848. // Check
  56849. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56850. return;
  56851. if (this._currentRenderId === this._scene.getRenderId()) {
  56852. return;
  56853. }
  56854. this._currentRenderId = this._scene.getRenderId();
  56855. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56856. // determine the number of particles we need to create
  56857. var newParticles;
  56858. if (this.manualEmitCount > -1) {
  56859. newParticles = this.manualEmitCount;
  56860. this._newPartsExcess = 0;
  56861. this.manualEmitCount = 0;
  56862. }
  56863. else {
  56864. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56865. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56866. }
  56867. if (this._newPartsExcess > 1.0) {
  56868. newParticles += this._newPartsExcess >> 0;
  56869. this._newPartsExcess -= this._newPartsExcess >> 0;
  56870. }
  56871. this._alive = false;
  56872. if (!this._stopped) {
  56873. this._actualFrame += this._scaledUpdateSpeed;
  56874. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56875. this.stop();
  56876. }
  56877. else {
  56878. newParticles = 0;
  56879. }
  56880. this._update(newParticles);
  56881. // Stopped?
  56882. if (this._stopped) {
  56883. if (!this._alive) {
  56884. this._started = false;
  56885. if (this.onAnimationEnd) {
  56886. this.onAnimationEnd();
  56887. }
  56888. if (this.disposeOnStop) {
  56889. this._scene._toBeDisposed.push(this);
  56890. }
  56891. }
  56892. }
  56893. // Animation sheet
  56894. if (this._isAnimationSheetEnabled) {
  56895. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56896. }
  56897. else {
  56898. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56899. }
  56900. // Update VBO
  56901. var offset = 0;
  56902. for (var index = 0; index < this._particles.length; index++) {
  56903. var particle = this._particles[index];
  56904. this._appendParticleVertexes(offset, particle);
  56905. offset += 4;
  56906. }
  56907. if (this._vertexBuffer) {
  56908. this._vertexBuffer.update(this._vertexData);
  56909. }
  56910. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56911. this.stop();
  56912. }
  56913. };
  56914. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56915. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56916. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56917. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56918. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56919. };
  56920. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56921. this._appendParticleVertex(offset++, particle, 0, 0);
  56922. this._appendParticleVertex(offset++, particle, 1, 0);
  56923. this._appendParticleVertex(offset++, particle, 1, 1);
  56924. this._appendParticleVertex(offset++, particle, 0, 1);
  56925. };
  56926. /**
  56927. * Rebuilds the particle system.
  56928. */
  56929. ParticleSystem.prototype.rebuild = function () {
  56930. this._createIndexBuffer();
  56931. if (this._vertexBuffer) {
  56932. this._vertexBuffer._rebuild();
  56933. }
  56934. };
  56935. /**
  56936. * Is this system ready to be used/rendered
  56937. * @return true if the system is ready
  56938. */
  56939. ParticleSystem.prototype.isReady = function () {
  56940. var effect = this._getEffect();
  56941. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56942. return false;
  56943. }
  56944. return true;
  56945. };
  56946. /**
  56947. * Renders the particle system in its current state.
  56948. * @returns the current number of particles
  56949. */
  56950. ParticleSystem.prototype.render = function () {
  56951. var effect = this._getEffect();
  56952. // Check
  56953. if (!this.isReady() || !this._particles.length) {
  56954. return 0;
  56955. }
  56956. var engine = this._scene.getEngine();
  56957. // Render
  56958. engine.enableEffect(effect);
  56959. engine.setState(false);
  56960. var viewMatrix = this._scene.getViewMatrix();
  56961. effect.setTexture("diffuseSampler", this.particleTexture);
  56962. effect.setMatrix("view", viewMatrix);
  56963. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56964. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56965. var baseSize = this.particleTexture.getBaseSize();
  56966. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56967. }
  56968. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56969. if (this._scene.clipPlane) {
  56970. var clipPlane = this._scene.clipPlane;
  56971. var invView = viewMatrix.clone();
  56972. invView.invert();
  56973. effect.setMatrix("invView", invView);
  56974. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56975. }
  56976. // VBOs
  56977. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56978. // Draw order
  56979. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56980. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56981. }
  56982. else {
  56983. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56984. }
  56985. if (this.forceDepthWrite) {
  56986. engine.setDepthWrite(true);
  56987. }
  56988. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56989. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56990. return this._particles.length;
  56991. };
  56992. /**
  56993. * Disposes the particle system and free the associated resources
  56994. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56995. */
  56996. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56997. if (disposeTexture === void 0) { disposeTexture = true; }
  56998. if (this._vertexBuffer) {
  56999. this._vertexBuffer.dispose();
  57000. this._vertexBuffer = null;
  57001. }
  57002. if (this._indexBuffer) {
  57003. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57004. this._indexBuffer = null;
  57005. }
  57006. if (disposeTexture && this.particleTexture) {
  57007. this.particleTexture.dispose();
  57008. this.particleTexture = null;
  57009. }
  57010. this._removeFromRoot();
  57011. // Remove from scene
  57012. var index = this._scene.particleSystems.indexOf(this);
  57013. if (index > -1) {
  57014. this._scene.particleSystems.splice(index, 1);
  57015. }
  57016. // Callback
  57017. this.onDisposeObservable.notifyObservers(this);
  57018. this.onDisposeObservable.clear();
  57019. };
  57020. /**
  57021. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  57022. * @param radius The radius of the sphere to emit from
  57023. * @returns the emitter
  57024. */
  57025. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  57026. if (radius === void 0) { radius = 1; }
  57027. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  57028. this.particleEmitterType = particleEmitter;
  57029. return particleEmitter;
  57030. };
  57031. /**
  57032. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  57033. * @param radius The radius of the sphere to emit from
  57034. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57035. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57036. * @returns the emitter
  57037. */
  57038. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57039. if (radius === void 0) { radius = 1; }
  57040. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57041. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57042. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57043. this.particleEmitterType = particleEmitter;
  57044. return particleEmitter;
  57045. };
  57046. /**
  57047. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  57048. * @param radius The radius of the cone to emit from
  57049. * @param angle The base angle of the cone
  57050. * @returns the emitter
  57051. */
  57052. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57053. if (radius === void 0) { radius = 1; }
  57054. if (angle === void 0) { angle = Math.PI / 4; }
  57055. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57056. this.particleEmitterType = particleEmitter;
  57057. return particleEmitter;
  57058. };
  57059. // 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.
  57060. /**
  57061. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57062. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57063. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57064. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57065. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57066. * @returns the emitter
  57067. */
  57068. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57069. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57070. this.particleEmitterType = particleEmitter;
  57071. this.direction1 = direction1;
  57072. this.direction2 = direction2;
  57073. this.minEmitBox = minEmitBox;
  57074. this.maxEmitBox = maxEmitBox;
  57075. return particleEmitter;
  57076. };
  57077. // Clone
  57078. /**
  57079. * Clones the particle system.
  57080. * @param name The name of the cloned object
  57081. * @param newEmitter The new emitter to use
  57082. * @returns the cloned particle system
  57083. */
  57084. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57085. var custom = null;
  57086. var program = null;
  57087. if (this.customShader != null) {
  57088. program = this.customShader;
  57089. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57090. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57091. }
  57092. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57093. result.customShader = program;
  57094. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57095. if (newEmitter === undefined) {
  57096. newEmitter = this.emitter;
  57097. }
  57098. result.emitter = newEmitter;
  57099. if (this.particleTexture) {
  57100. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57101. }
  57102. if (!this.preventAutoStart) {
  57103. result.start();
  57104. }
  57105. return result;
  57106. };
  57107. /**
  57108. * Serializes the particle system to a JSON object.
  57109. * @returns the JSON object
  57110. */
  57111. ParticleSystem.prototype.serialize = function () {
  57112. var serializationObject = {};
  57113. serializationObject.name = this.name;
  57114. serializationObject.id = this.id;
  57115. // Emitter
  57116. if (this.emitter.position) {
  57117. var emitterMesh = this.emitter;
  57118. serializationObject.emitterId = emitterMesh.id;
  57119. }
  57120. else {
  57121. var emitterPosition = this.emitter;
  57122. serializationObject.emitter = emitterPosition.asArray();
  57123. }
  57124. serializationObject.capacity = this.getCapacity();
  57125. if (this.particleTexture) {
  57126. serializationObject.textureName = this.particleTexture.name;
  57127. }
  57128. // Animations
  57129. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57130. // Particle system
  57131. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57132. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57133. serializationObject.minSize = this.minSize;
  57134. serializationObject.maxSize = this.maxSize;
  57135. serializationObject.minScaleX = this.minScaleX;
  57136. serializationObject.maxScaleX = this.maxScaleX;
  57137. serializationObject.minScaleY = this.minScaleY;
  57138. serializationObject.maxScaleY = this.maxScaleY;
  57139. serializationObject.minEmitPower = this.minEmitPower;
  57140. serializationObject.maxEmitPower = this.maxEmitPower;
  57141. serializationObject.minLifeTime = this.minLifeTime;
  57142. serializationObject.maxLifeTime = this.maxLifeTime;
  57143. serializationObject.emitRate = this.emitRate;
  57144. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57145. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57146. serializationObject.gravity = this.gravity.asArray();
  57147. serializationObject.direction1 = this.direction1.asArray();
  57148. serializationObject.direction2 = this.direction2.asArray();
  57149. serializationObject.color1 = this.color1.asArray();
  57150. serializationObject.color2 = this.color2.asArray();
  57151. serializationObject.colorDead = this.colorDead.asArray();
  57152. serializationObject.updateSpeed = this.updateSpeed;
  57153. serializationObject.targetStopDuration = this.targetStopDuration;
  57154. serializationObject.textureMask = this.textureMask.asArray();
  57155. serializationObject.blendMode = this.blendMode;
  57156. serializationObject.customShader = this.customShader;
  57157. serializationObject.preventAutoStart = this.preventAutoStart;
  57158. serializationObject.startSpriteCellID = this.startSpriteCellID;
  57159. serializationObject.endSpriteCellID = this.endSpriteCellID;
  57160. serializationObject.spriteCellLoop = this.spriteCellLoop;
  57161. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  57162. serializationObject.spriteCellWidth = this.spriteCellWidth;
  57163. serializationObject.spriteCellHeight = this.spriteCellHeight;
  57164. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57165. // Emitter
  57166. if (this.particleEmitterType) {
  57167. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57168. }
  57169. return serializationObject;
  57170. };
  57171. /**
  57172. * Parses a JSON object to create a particle system.
  57173. * @param parsedParticleSystem The JSON object to parse
  57174. * @param scene The scene to create the particle system in
  57175. * @param rootUrl The root url to use to load external dependencies like texture
  57176. * @returns the Parsed particle system
  57177. */
  57178. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57179. var name = parsedParticleSystem.name;
  57180. var custom = null;
  57181. var program = null;
  57182. if (parsedParticleSystem.customShader) {
  57183. program = parsedParticleSystem.customShader;
  57184. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57185. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57186. }
  57187. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57188. particleSystem.customShader = program;
  57189. if (parsedParticleSystem.id) {
  57190. particleSystem.id = parsedParticleSystem.id;
  57191. }
  57192. // Auto start
  57193. if (parsedParticleSystem.preventAutoStart) {
  57194. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57195. }
  57196. // Texture
  57197. if (parsedParticleSystem.textureName) {
  57198. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57199. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57200. }
  57201. // Emitter
  57202. if (parsedParticleSystem.emitterId) {
  57203. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57204. }
  57205. else {
  57206. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57207. }
  57208. // Animations
  57209. if (parsedParticleSystem.animations) {
  57210. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57211. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57212. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57213. }
  57214. }
  57215. if (parsedParticleSystem.autoAnimate) {
  57216. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57217. }
  57218. // Particle system
  57219. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57220. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57221. particleSystem.minSize = parsedParticleSystem.minSize;
  57222. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57223. if (parsedParticleSystem.minScaleX) {
  57224. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57225. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57226. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57227. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57228. }
  57229. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57230. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57231. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57232. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57233. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57234. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57235. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57236. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57237. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57238. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57239. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57240. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57241. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57242. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57243. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57244. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57245. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57246. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57247. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57248. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57249. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57250. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57251. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57252. if (!particleSystem.preventAutoStart) {
  57253. particleSystem.start();
  57254. }
  57255. return particleSystem;
  57256. };
  57257. /**
  57258. * Source color is added to the destination color without alpha affecting the result.
  57259. */
  57260. ParticleSystem.BLENDMODE_ONEONE = 0;
  57261. /**
  57262. * Blend current color and particle color using particle’s alpha.
  57263. */
  57264. ParticleSystem.BLENDMODE_STANDARD = 1;
  57265. return ParticleSystem;
  57266. }());
  57267. BABYLON.ParticleSystem = ParticleSystem;
  57268. })(BABYLON || (BABYLON = {}));
  57269. //# sourceMappingURL=babylon.particleSystem.js.map
  57270. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57271. var BABYLON;
  57272. (function (BABYLON) {
  57273. /**
  57274. * Particle emitter emitting particles from the inside of a box.
  57275. * It emits the particles randomly between 2 given directions.
  57276. */
  57277. var BoxParticleEmitter = /** @class */ (function () {
  57278. /**
  57279. * Creates a new instance BoxParticleEmitter
  57280. */
  57281. function BoxParticleEmitter() {
  57282. /**
  57283. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57284. */
  57285. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57286. /**
  57287. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57288. */
  57289. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57290. /**
  57291. * 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.
  57292. */
  57293. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57294. /**
  57295. * 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.
  57296. */
  57297. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57298. }
  57299. /**
  57300. * Called by the particle System when the direction is computed for the created particle.
  57301. * @param emitPower is the power of the particle (speed)
  57302. * @param worldMatrix is the world matrix of the particle system
  57303. * @param directionToUpdate is the direction vector to update with the result
  57304. * @param particle is the particle we are computed the direction for
  57305. */
  57306. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57307. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57308. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57309. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57310. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57311. };
  57312. /**
  57313. * Called by the particle System when the position is computed for the created particle.
  57314. * @param worldMatrix is the world matrix of the particle system
  57315. * @param positionToUpdate is the position vector to update with the result
  57316. * @param particle is the particle we are computed the position for
  57317. */
  57318. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57319. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57320. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57321. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57322. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57323. };
  57324. /**
  57325. * Clones the current emitter and returns a copy of it
  57326. * @returns the new emitter
  57327. */
  57328. BoxParticleEmitter.prototype.clone = function () {
  57329. var newOne = new BoxParticleEmitter();
  57330. BABYLON.Tools.DeepCopy(this, newOne);
  57331. return newOne;
  57332. };
  57333. /**
  57334. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57335. * @param effect defines the update shader
  57336. */
  57337. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57338. effect.setVector3("direction1", this.direction1);
  57339. effect.setVector3("direction2", this.direction2);
  57340. effect.setVector3("minEmitBox", this.minEmitBox);
  57341. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57342. };
  57343. /**
  57344. * Returns a string to use to update the GPU particles update shader
  57345. * @returns a string containng the defines string
  57346. */
  57347. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57348. return "#define BOXEMITTER";
  57349. };
  57350. /**
  57351. * Returns the string "BoxEmitter"
  57352. * @returns a string containing the class name
  57353. */
  57354. BoxParticleEmitter.prototype.getClassName = function () {
  57355. return "BoxEmitter";
  57356. };
  57357. /**
  57358. * Serializes the particle system to a JSON object.
  57359. * @returns the JSON object
  57360. */
  57361. BoxParticleEmitter.prototype.serialize = function () {
  57362. var serializationObject = {};
  57363. serializationObject.type = this.getClassName();
  57364. serializationObject.direction1 = this.direction1.asArray();
  57365. serializationObject.direction2 = this.direction2.asArray();
  57366. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57367. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57368. return serializationObject;
  57369. };
  57370. /**
  57371. * Parse properties from a JSON object
  57372. * @param serializationObject defines the JSON object
  57373. */
  57374. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57375. this.direction1.copyFrom(serializationObject.direction1);
  57376. this.direction2.copyFrom(serializationObject.direction2);
  57377. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57378. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57379. };
  57380. return BoxParticleEmitter;
  57381. }());
  57382. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57383. })(BABYLON || (BABYLON = {}));
  57384. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57385. var BABYLON;
  57386. (function (BABYLON) {
  57387. /**
  57388. * Particle emitter emitting particles from the inside of a cone.
  57389. * It emits the particles alongside the cone volume from the base to the particle.
  57390. * The emission direction might be randomized.
  57391. */
  57392. var ConeParticleEmitter = /** @class */ (function () {
  57393. /**
  57394. * Creates a new instance ConeParticleEmitter
  57395. * @param radius the radius of the emission cone (1 by default)
  57396. * @param angles the cone base angle (PI by default)
  57397. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57398. */
  57399. function ConeParticleEmitter(radius, angle,
  57400. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57401. directionRandomizer) {
  57402. if (radius === void 0) { radius = 1; }
  57403. if (angle === void 0) { angle = Math.PI; }
  57404. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57405. this.directionRandomizer = directionRandomizer;
  57406. this.angle = angle;
  57407. this.radius = radius;
  57408. }
  57409. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57410. /**
  57411. * Gets or sets the radius of the emission cone
  57412. */
  57413. get: function () {
  57414. return this._radius;
  57415. },
  57416. set: function (value) {
  57417. this._radius = value;
  57418. this._buildHeight();
  57419. },
  57420. enumerable: true,
  57421. configurable: true
  57422. });
  57423. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57424. /**
  57425. * Gets or sets the angle of the emission cone
  57426. */
  57427. get: function () {
  57428. return this._angle;
  57429. },
  57430. set: function (value) {
  57431. this._angle = value;
  57432. this._buildHeight();
  57433. },
  57434. enumerable: true,
  57435. configurable: true
  57436. });
  57437. ConeParticleEmitter.prototype._buildHeight = function () {
  57438. if (this._angle !== 0) {
  57439. this._height = this._radius / Math.tan(this._angle / 2);
  57440. }
  57441. else {
  57442. this._height = 1;
  57443. }
  57444. };
  57445. /**
  57446. * Called by the particle System when the direction is computed for the created particle.
  57447. * @param emitPower is the power of the particle (speed)
  57448. * @param worldMatrix is the world matrix of the particle system
  57449. * @param directionToUpdate is the direction vector to update with the result
  57450. * @param particle is the particle we are computed the direction for
  57451. */
  57452. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57453. if (this._angle === 0) {
  57454. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57455. }
  57456. else {
  57457. // measure the direction Vector from the emitter to the particle.
  57458. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57459. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57460. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57461. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57462. direction.x += randX;
  57463. direction.y += randY;
  57464. direction.z += randZ;
  57465. direction.normalize();
  57466. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57467. }
  57468. };
  57469. /**
  57470. * Called by the particle System when the position is computed for the created particle.
  57471. * @param worldMatrix is the world matrix of the particle system
  57472. * @param positionToUpdate is the position vector to update with the result
  57473. * @param particle is the particle we are computed the position for
  57474. */
  57475. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57476. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57477. var h = BABYLON.Scalar.RandomRange(0, 1);
  57478. // Better distribution in a cone at normal angles.
  57479. h = 1 - h * h;
  57480. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57481. radius = radius * h;
  57482. var randX = radius * Math.sin(s);
  57483. var randZ = radius * Math.cos(s);
  57484. var randY = h * this._height;
  57485. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57486. };
  57487. /**
  57488. * Clones the current emitter and returns a copy of it
  57489. * @returns the new emitter
  57490. */
  57491. ConeParticleEmitter.prototype.clone = function () {
  57492. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57493. BABYLON.Tools.DeepCopy(this, newOne);
  57494. return newOne;
  57495. };
  57496. /**
  57497. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57498. * @param effect defines the update shader
  57499. */
  57500. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57501. effect.setFloat("radius", this._radius);
  57502. effect.setFloat("coneAngle", this._angle);
  57503. effect.setFloat("height", this._height);
  57504. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57505. };
  57506. /**
  57507. * Returns a string to use to update the GPU particles update shader
  57508. * @returns a string containng the defines string
  57509. */
  57510. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57511. return "#define CONEEMITTER";
  57512. };
  57513. /**
  57514. * Returns the string "BoxEmitter"
  57515. * @returns a string containing the class name
  57516. */
  57517. ConeParticleEmitter.prototype.getClassName = function () {
  57518. return "ConeEmitter";
  57519. };
  57520. /**
  57521. * Serializes the particle system to a JSON object.
  57522. * @returns the JSON object
  57523. */
  57524. ConeParticleEmitter.prototype.serialize = function () {
  57525. var serializationObject = {};
  57526. serializationObject.type = this.getClassName();
  57527. serializationObject.radius = this._radius;
  57528. serializationObject.angle = this._angle;
  57529. serializationObject.directionRandomizer = this.directionRandomizer;
  57530. return serializationObject;
  57531. };
  57532. /**
  57533. * Parse properties from a JSON object
  57534. * @param serializationObject defines the JSON object
  57535. */
  57536. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57537. this.radius = serializationObject.radius;
  57538. this.angle = serializationObject.angle;
  57539. this.directionRandomizer = serializationObject.directionRandomizer;
  57540. };
  57541. return ConeParticleEmitter;
  57542. }());
  57543. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57544. })(BABYLON || (BABYLON = {}));
  57545. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57546. var BABYLON;
  57547. (function (BABYLON) {
  57548. /**
  57549. * Particle emitter emitting particles from the inside of a sphere.
  57550. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57551. */
  57552. var SphereParticleEmitter = /** @class */ (function () {
  57553. /**
  57554. * Creates a new instance SphereParticleEmitter
  57555. * @param radius the radius of the emission sphere (1 by default)
  57556. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57557. */
  57558. function SphereParticleEmitter(
  57559. /**
  57560. * The radius of the emission sphere.
  57561. */
  57562. radius,
  57563. /**
  57564. * How much to randomize the particle direction [0-1].
  57565. */
  57566. directionRandomizer) {
  57567. if (radius === void 0) { radius = 1; }
  57568. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57569. this.radius = radius;
  57570. this.directionRandomizer = directionRandomizer;
  57571. }
  57572. /**
  57573. * Called by the particle System when the direction is computed for the created particle.
  57574. * @param emitPower is the power of the particle (speed)
  57575. * @param worldMatrix is the world matrix of the particle system
  57576. * @param directionToUpdate is the direction vector to update with the result
  57577. * @param particle is the particle we are computed the direction for
  57578. */
  57579. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57580. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57581. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57582. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57583. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57584. direction.x += randX;
  57585. direction.y += randY;
  57586. direction.z += randZ;
  57587. direction.normalize();
  57588. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57589. };
  57590. /**
  57591. * Called by the particle System when the position is computed for the created particle.
  57592. * @param worldMatrix is the world matrix of the particle system
  57593. * @param positionToUpdate is the position vector to update with the result
  57594. * @param particle is the particle we are computed the position for
  57595. */
  57596. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57597. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57598. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57599. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57600. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57601. var randY = randRadius * Math.cos(theta);
  57602. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57603. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57604. };
  57605. /**
  57606. * Clones the current emitter and returns a copy of it
  57607. * @returns the new emitter
  57608. */
  57609. SphereParticleEmitter.prototype.clone = function () {
  57610. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57611. BABYLON.Tools.DeepCopy(this, newOne);
  57612. return newOne;
  57613. };
  57614. /**
  57615. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57616. * @param effect defines the update shader
  57617. */
  57618. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57619. effect.setFloat("radius", this.radius);
  57620. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57621. };
  57622. /**
  57623. * Returns a string to use to update the GPU particles update shader
  57624. * @returns a string containng the defines string
  57625. */
  57626. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57627. return "#define SPHEREEMITTER";
  57628. };
  57629. /**
  57630. * Returns the string "SphereParticleEmitter"
  57631. * @returns a string containing the class name
  57632. */
  57633. SphereParticleEmitter.prototype.getClassName = function () {
  57634. return "SphereParticleEmitter";
  57635. };
  57636. /**
  57637. * Serializes the particle system to a JSON object.
  57638. * @returns the JSON object
  57639. */
  57640. SphereParticleEmitter.prototype.serialize = function () {
  57641. var serializationObject = {};
  57642. serializationObject.type = this.getClassName();
  57643. serializationObject.radius = this.radius;
  57644. serializationObject.directionRandomizer = this.directionRandomizer;
  57645. return serializationObject;
  57646. };
  57647. /**
  57648. * Parse properties from a JSON object
  57649. * @param serializationObject defines the JSON object
  57650. */
  57651. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57652. this.radius = serializationObject.radius;
  57653. this.directionRandomizer = serializationObject.directionRandomizer;
  57654. };
  57655. return SphereParticleEmitter;
  57656. }());
  57657. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57658. /**
  57659. * Particle emitter emitting particles from the inside of a sphere.
  57660. * It emits the particles randomly between two vectors.
  57661. */
  57662. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57663. __extends(SphereDirectedParticleEmitter, _super);
  57664. /**
  57665. * Creates a new instance SphereDirectedParticleEmitter
  57666. * @param radius the radius of the emission sphere (1 by default)
  57667. * @param direction1 the min limit of the emission direction (up vector by default)
  57668. * @param direction2 the max limit of the emission direction (up vector by default)
  57669. */
  57670. function SphereDirectedParticleEmitter(radius,
  57671. /**
  57672. * The min limit of the emission direction.
  57673. */
  57674. direction1,
  57675. /**
  57676. * The max limit of the emission direction.
  57677. */
  57678. direction2) {
  57679. if (radius === void 0) { radius = 1; }
  57680. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57681. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57682. var _this = _super.call(this, radius) || this;
  57683. _this.direction1 = direction1;
  57684. _this.direction2 = direction2;
  57685. return _this;
  57686. }
  57687. /**
  57688. * Called by the particle System when the direction is computed for the created particle.
  57689. * @param emitPower is the power of the particle (speed)
  57690. * @param worldMatrix is the world matrix of the particle system
  57691. * @param directionToUpdate is the direction vector to update with the result
  57692. * @param particle is the particle we are computed the direction for
  57693. */
  57694. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57695. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57696. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57697. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57698. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57699. };
  57700. /**
  57701. * Clones the current emitter and returns a copy of it
  57702. * @returns the new emitter
  57703. */
  57704. SphereDirectedParticleEmitter.prototype.clone = function () {
  57705. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57706. BABYLON.Tools.DeepCopy(this, newOne);
  57707. return newOne;
  57708. };
  57709. /**
  57710. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57711. * @param effect defines the update shader
  57712. */
  57713. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57714. effect.setFloat("radius", this.radius);
  57715. effect.setVector3("direction1", this.direction1);
  57716. effect.setVector3("direction2", this.direction2);
  57717. };
  57718. /**
  57719. * Returns a string to use to update the GPU particles update shader
  57720. * @returns a string containng the defines string
  57721. */
  57722. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57723. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57724. };
  57725. /**
  57726. * Returns the string "SphereDirectedParticleEmitter"
  57727. * @returns a string containing the class name
  57728. */
  57729. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57730. return "SphereDirectedParticleEmitter";
  57731. };
  57732. /**
  57733. * Serializes the particle system to a JSON object.
  57734. * @returns the JSON object
  57735. */
  57736. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57737. var serializationObject = _super.prototype.serialize.call(this);
  57738. serializationObject.direction1 = this.direction1.asArray();
  57739. serializationObject.direction2 = this.direction2.asArray();
  57740. return serializationObject;
  57741. };
  57742. /**
  57743. * Parse properties from a JSON object
  57744. * @param serializationObject defines the JSON object
  57745. */
  57746. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57747. _super.prototype.parse.call(this, serializationObject);
  57748. this.direction1.copyFrom(serializationObject.direction1);
  57749. this.direction2.copyFrom(serializationObject.direction2);
  57750. };
  57751. return SphereDirectedParticleEmitter;
  57752. }(SphereParticleEmitter));
  57753. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57754. })(BABYLON || (BABYLON = {}));
  57755. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57756. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57757. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57758. s = arguments[i];
  57759. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57760. t[p] = s[p];
  57761. }
  57762. return t;
  57763. };
  57764. var BABYLON;
  57765. (function (BABYLON) {
  57766. /**
  57767. * This represents a GPU particle system in Babylon
  57768. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57769. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57770. */
  57771. var GPUParticleSystem = /** @class */ (function () {
  57772. /**
  57773. * Instantiates a GPU particle system.
  57774. * 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.
  57775. * @param name The name of the particle system
  57776. * @param capacity The max number of particles alive at the same time
  57777. * @param scene The scene the particle system belongs to
  57778. */
  57779. function GPUParticleSystem(name, options, scene) {
  57780. /**
  57781. * The emitter represents the Mesh or position we are attaching the particle system to.
  57782. */
  57783. this.emitter = null;
  57784. /**
  57785. * The rendering group used by the Particle system to chose when to render.
  57786. */
  57787. this.renderingGroupId = 0;
  57788. /**
  57789. * The layer mask we are rendering the particles through.
  57790. */
  57791. this.layerMask = 0x0FFFFFFF;
  57792. this._targetIndex = 0;
  57793. this._currentRenderId = -1;
  57794. this._started = false;
  57795. this._stopped = false;
  57796. this._timeDelta = 0;
  57797. this._attributesStrideSize = 18;
  57798. this._actualFrame = 0;
  57799. /**
  57800. * List of animations used by the particle system.
  57801. */
  57802. this.animations = [];
  57803. /**
  57804. * An event triggered when the system is disposed.
  57805. */
  57806. this.onDisposeObservable = new BABYLON.Observable();
  57807. /**
  57808. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57809. */
  57810. this.updateSpeed = 0.01;
  57811. /**
  57812. * The amount of time the particle system is running (depends of the overall update speed).
  57813. */
  57814. this.targetStopDuration = 0;
  57815. /**
  57816. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57817. */
  57818. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57819. /**
  57820. * Minimum life time of emitting particles.
  57821. */
  57822. this.minLifeTime = 1;
  57823. /**
  57824. * Maximum life time of emitting particles.
  57825. */
  57826. this.maxLifeTime = 1;
  57827. /**
  57828. * Minimum Size of emitting particles.
  57829. */
  57830. this.minSize = 1;
  57831. /**
  57832. * Maximum Size of emitting particles.
  57833. */
  57834. this.maxSize = 1;
  57835. /**
  57836. * Minimum scale of emitting particles on X axis.
  57837. */
  57838. this.minScaleX = 1;
  57839. /**
  57840. * Maximum scale of emitting particles on X axis.
  57841. */
  57842. this.maxScaleX = 1;
  57843. /**
  57844. * Minimum scale of emitting particles on Y axis.
  57845. */
  57846. this.minScaleY = 1;
  57847. /**
  57848. * Maximum scale of emitting particles on Y axis.
  57849. */
  57850. this.maxScaleY = 1;
  57851. /**
  57852. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57853. */
  57854. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57855. /**
  57856. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57857. */
  57858. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57859. /**
  57860. * Color the particle will have at the end of its lifetime.
  57861. */
  57862. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57863. /**
  57864. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57865. */
  57866. this.emitRate = 100;
  57867. /**
  57868. * You can use gravity if you want to give an orientation to your particles.
  57869. */
  57870. this.gravity = BABYLON.Vector3.Zero();
  57871. /**
  57872. * Minimum power of emitting particles.
  57873. */
  57874. this.minEmitPower = 1;
  57875. /**
  57876. * Maximum power of emitting particles.
  57877. */
  57878. this.maxEmitPower = 1;
  57879. /**
  57880. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57881. */
  57882. this.minAngularSpeed = 0;
  57883. /**
  57884. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57885. */
  57886. this.maxAngularSpeed = 0;
  57887. /**
  57888. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57889. * to override the particles.
  57890. */
  57891. this.forceDepthWrite = false;
  57892. this.id = name;
  57893. this.name = name;
  57894. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57895. this._engine = this._scene.getEngine();
  57896. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57897. this._capacity = fullOptions.capacity;
  57898. this._activeCount = fullOptions.capacity;
  57899. this._currentActiveCount = 0;
  57900. this._scene.particleSystems.push(this);
  57901. this._updateEffectOptions = {
  57902. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57903. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57904. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57905. "angleRange"],
  57906. uniformBuffersNames: [],
  57907. samplers: ["randomSampler"],
  57908. defines: "",
  57909. fallbacks: null,
  57910. onCompiled: null,
  57911. onError: null,
  57912. indexParameters: null,
  57913. maxSimultaneousLights: 0,
  57914. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57915. };
  57916. // Random data
  57917. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57918. var d = [];
  57919. for (var i = 0; i < maxTextureSize; ++i) {
  57920. d.push(Math.random());
  57921. d.push(Math.random());
  57922. d.push(Math.random());
  57923. d.push(Math.random());
  57924. }
  57925. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57926. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57927. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57928. this._randomTextureSize = maxTextureSize;
  57929. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57930. }
  57931. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57932. /**
  57933. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57934. */
  57935. get: function () {
  57936. if (!BABYLON.Engine.LastCreatedEngine) {
  57937. return false;
  57938. }
  57939. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57940. },
  57941. enumerable: true,
  57942. configurable: true
  57943. });
  57944. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57945. /**
  57946. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57947. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57948. */
  57949. get: function () {
  57950. if (this.particleEmitterType.direction1) {
  57951. return this.particleEmitterType.direction1;
  57952. }
  57953. return BABYLON.Vector3.Zero();
  57954. },
  57955. set: function (value) {
  57956. if (this.particleEmitterType.direction1) {
  57957. this.particleEmitterType.direction1 = value;
  57958. }
  57959. },
  57960. enumerable: true,
  57961. configurable: true
  57962. });
  57963. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57964. /**
  57965. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57966. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57967. */
  57968. get: function () {
  57969. if (this.particleEmitterType.direction2) {
  57970. return this.particleEmitterType.direction2;
  57971. }
  57972. return BABYLON.Vector3.Zero();
  57973. },
  57974. set: function (value) {
  57975. if (this.particleEmitterType.direction2) {
  57976. this.particleEmitterType.direction2 = value;
  57977. }
  57978. },
  57979. enumerable: true,
  57980. configurable: true
  57981. });
  57982. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57983. /**
  57984. * 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.
  57985. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57986. */
  57987. get: function () {
  57988. if (this.particleEmitterType.minEmitBox) {
  57989. return this.particleEmitterType.minEmitBox;
  57990. }
  57991. return BABYLON.Vector3.Zero();
  57992. },
  57993. set: function (value) {
  57994. if (this.particleEmitterType.minEmitBox) {
  57995. this.particleEmitterType.minEmitBox = value;
  57996. }
  57997. },
  57998. enumerable: true,
  57999. configurable: true
  58000. });
  58001. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  58002. /**
  58003. * 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.
  58004. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58005. */
  58006. get: function () {
  58007. if (this.particleEmitterType.maxEmitBox) {
  58008. return this.particleEmitterType.maxEmitBox;
  58009. }
  58010. return BABYLON.Vector3.Zero();
  58011. },
  58012. set: function (value) {
  58013. if (this.particleEmitterType.maxEmitBox) {
  58014. this.particleEmitterType.maxEmitBox = value;
  58015. }
  58016. },
  58017. enumerable: true,
  58018. configurable: true
  58019. });
  58020. /**
  58021. * Gets the maximum number of particles active at the same time.
  58022. * @returns The max number of active particles.
  58023. */
  58024. GPUParticleSystem.prototype.getCapacity = function () {
  58025. return this._capacity;
  58026. };
  58027. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  58028. /**
  58029. * Gets or set the number of active particles
  58030. */
  58031. get: function () {
  58032. return this._activeCount;
  58033. },
  58034. set: function (value) {
  58035. this._activeCount = Math.min(value, this._capacity);
  58036. },
  58037. enumerable: true,
  58038. configurable: true
  58039. });
  58040. /**
  58041. * Is this system ready to be used/rendered
  58042. * @return true if the system is ready
  58043. */
  58044. GPUParticleSystem.prototype.isReady = function () {
  58045. if (!this._updateEffect) {
  58046. this._recreateUpdateEffect();
  58047. this._recreateRenderEffect();
  58048. return false;
  58049. }
  58050. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58051. return false;
  58052. }
  58053. return true;
  58054. };
  58055. /**
  58056. * Gets Wether the system has been started.
  58057. * @returns True if it has been started, otherwise false.
  58058. */
  58059. GPUParticleSystem.prototype.isStarted = function () {
  58060. return this._started;
  58061. };
  58062. /**
  58063. * Starts the particle system and begins to emit.
  58064. */
  58065. GPUParticleSystem.prototype.start = function () {
  58066. this._started = true;
  58067. this._stopped = false;
  58068. };
  58069. /**
  58070. * Stops the particle system.
  58071. */
  58072. GPUParticleSystem.prototype.stop = function () {
  58073. this._stopped = true;
  58074. };
  58075. /**
  58076. * Remove all active particles
  58077. */
  58078. GPUParticleSystem.prototype.reset = function () {
  58079. this._releaseBuffers();
  58080. this._releaseVAOs();
  58081. this._currentActiveCount = 0;
  58082. this._targetIndex = 0;
  58083. };
  58084. /**
  58085. * Returns the string "GPUParticleSystem"
  58086. * @returns a string containing the class name
  58087. */
  58088. GPUParticleSystem.prototype.getClassName = function () {
  58089. return "GPUParticleSystem";
  58090. };
  58091. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  58092. var updateVertexBuffers = {};
  58093. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  58094. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  58095. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  58096. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  58097. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3);
  58098. updateVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4);
  58099. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 13, 3);
  58100. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2);
  58101. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  58102. this._engine.bindArrayBuffer(null);
  58103. return vao;
  58104. };
  58105. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  58106. var renderVertexBuffers = {};
  58107. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  58108. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  58109. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  58110. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3, this._attributesStrideSize, true);
  58111. renderVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4, this._attributesStrideSize, true);
  58112. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2, this._attributesStrideSize, true);
  58113. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  58114. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  58115. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  58116. this._engine.bindArrayBuffer(null);
  58117. return vao;
  58118. };
  58119. GPUParticleSystem.prototype._initialize = function (force) {
  58120. if (force === void 0) { force = false; }
  58121. if (this._buffer0 && !force) {
  58122. return;
  58123. }
  58124. var engine = this._scene.getEngine();
  58125. var data = new Array();
  58126. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  58127. // position
  58128. data.push(0.0);
  58129. data.push(0.0);
  58130. data.push(0.0);
  58131. // Age and life
  58132. data.push(0.0); // create the particle as a dead one to create a new one at start
  58133. data.push(0.0);
  58134. // Seed
  58135. data.push(Math.random());
  58136. // Size
  58137. data.push(0.0);
  58138. data.push(0.0);
  58139. data.push(0.0);
  58140. // color
  58141. data.push(0.0);
  58142. data.push(0.0);
  58143. data.push(0.0);
  58144. data.push(0.0);
  58145. // direction
  58146. data.push(0.0);
  58147. data.push(0.0);
  58148. data.push(0.0);
  58149. // angle
  58150. data.push(0.0);
  58151. data.push(0.0);
  58152. }
  58153. // Sprite data
  58154. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  58155. -0.5, 0.5, 0, 1,
  58156. -0.5, -0.5, 0, 0,
  58157. 0.5, -0.5, 1, 0]);
  58158. // Buffers
  58159. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58160. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58161. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  58162. // Update VAO
  58163. this._updateVAO = [];
  58164. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  58165. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  58166. // Render VAO
  58167. this._renderVAO = [];
  58168. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  58169. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  58170. // Links
  58171. this._sourceBuffer = this._buffer0;
  58172. this._targetBuffer = this._buffer1;
  58173. };
  58174. /** @hidden */
  58175. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  58176. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  58177. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  58178. return;
  58179. }
  58180. this._updateEffectOptions.defines = defines;
  58181. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  58182. };
  58183. /** @hidden */
  58184. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  58185. var defines = "";
  58186. if (this._scene.clipPlane) {
  58187. defines = "\n#define CLIPPLANE";
  58188. }
  58189. if (this._renderEffect && this._renderEffect.defines === defines) {
  58190. return;
  58191. }
  58192. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  58193. };
  58194. /**
  58195. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58196. */
  58197. GPUParticleSystem.prototype.animate = function () {
  58198. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  58199. this._actualFrame += this._timeDelta;
  58200. if (!this._stopped) {
  58201. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58202. this.stop();
  58203. }
  58204. }
  58205. };
  58206. /**
  58207. * Renders the particle system in its current state.
  58208. * @returns the current number of particles
  58209. */
  58210. GPUParticleSystem.prototype.render = function () {
  58211. if (!this._started) {
  58212. return 0;
  58213. }
  58214. this._recreateUpdateEffect();
  58215. this._recreateRenderEffect();
  58216. if (!this.isReady()) {
  58217. return 0;
  58218. }
  58219. if (this._currentRenderId === this._scene.getRenderId()) {
  58220. return 0;
  58221. }
  58222. this._currentRenderId = this._scene.getRenderId();
  58223. // Get everything ready to render
  58224. this._initialize();
  58225. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  58226. // Enable update effect
  58227. this._engine.enableEffect(this._updateEffect);
  58228. this._engine.setState(false);
  58229. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58230. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58231. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58232. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  58233. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58234. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58235. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58236. this._updateEffect.setDirectColor4("color1", this.color1);
  58237. this._updateEffect.setDirectColor4("color2", this.color2);
  58238. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58239. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  58240. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  58241. this._updateEffect.setVector3("gravity", this.gravity);
  58242. if (this.particleEmitterType) {
  58243. this.particleEmitterType.applyToShader(this._updateEffect);
  58244. }
  58245. var emitterWM;
  58246. if (this.emitter.position) {
  58247. var emitterMesh = this.emitter;
  58248. emitterWM = emitterMesh.getWorldMatrix();
  58249. }
  58250. else {
  58251. var emitterPosition = this.emitter;
  58252. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58253. }
  58254. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58255. // Bind source VAO
  58256. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58257. // Update
  58258. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58259. this._engine.setRasterizerState(false);
  58260. this._engine.beginTransformFeedback();
  58261. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58262. this._engine.endTransformFeedback();
  58263. this._engine.setRasterizerState(true);
  58264. this._engine.bindTransformFeedbackBuffer(null);
  58265. // Enable render effect
  58266. this._engine.enableEffect(this._renderEffect);
  58267. var viewMatrix = this._scene.getViewMatrix();
  58268. this._renderEffect.setMatrix("view", viewMatrix);
  58269. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58270. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58271. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58272. if (this._scene.clipPlane) {
  58273. var clipPlane = this._scene.clipPlane;
  58274. var invView = viewMatrix.clone();
  58275. invView.invert();
  58276. this._renderEffect.setMatrix("invView", invView);
  58277. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58278. }
  58279. // Draw order
  58280. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58281. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58282. }
  58283. else {
  58284. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58285. }
  58286. if (this.forceDepthWrite) {
  58287. this._engine.setDepthWrite(true);
  58288. }
  58289. // Bind source VAO
  58290. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58291. // Render
  58292. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58293. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58294. // Switch VAOs
  58295. this._targetIndex++;
  58296. if (this._targetIndex === 2) {
  58297. this._targetIndex = 0;
  58298. }
  58299. // Switch buffers
  58300. var tmpBuffer = this._sourceBuffer;
  58301. this._sourceBuffer = this._targetBuffer;
  58302. this._targetBuffer = tmpBuffer;
  58303. return this._currentActiveCount;
  58304. };
  58305. /**
  58306. * Rebuilds the particle system
  58307. */
  58308. GPUParticleSystem.prototype.rebuild = function () {
  58309. this._initialize(true);
  58310. };
  58311. GPUParticleSystem.prototype._releaseBuffers = function () {
  58312. if (this._buffer0) {
  58313. this._buffer0.dispose();
  58314. this._buffer0 = null;
  58315. }
  58316. if (this._buffer1) {
  58317. this._buffer1.dispose();
  58318. this._buffer1 = null;
  58319. }
  58320. if (this._spriteBuffer) {
  58321. this._spriteBuffer.dispose();
  58322. this._spriteBuffer = null;
  58323. }
  58324. };
  58325. GPUParticleSystem.prototype._releaseVAOs = function () {
  58326. if (!this._updateVAO) {
  58327. return;
  58328. }
  58329. for (var index = 0; index < this._updateVAO.length; index++) {
  58330. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58331. }
  58332. this._updateVAO = [];
  58333. for (var index = 0; index < this._renderVAO.length; index++) {
  58334. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58335. }
  58336. this._renderVAO = [];
  58337. };
  58338. /**
  58339. * Disposes the particle system and free the associated resources
  58340. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58341. */
  58342. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58343. if (disposeTexture === void 0) { disposeTexture = true; }
  58344. var index = this._scene.particleSystems.indexOf(this);
  58345. if (index > -1) {
  58346. this._scene.particleSystems.splice(index, 1);
  58347. }
  58348. this._releaseBuffers();
  58349. this._releaseVAOs();
  58350. if (this._randomTexture) {
  58351. this._randomTexture.dispose();
  58352. this._randomTexture = null;
  58353. }
  58354. if (disposeTexture && this.particleTexture) {
  58355. this.particleTexture.dispose();
  58356. this.particleTexture = null;
  58357. }
  58358. // Callback
  58359. this.onDisposeObservable.notifyObservers(this);
  58360. this.onDisposeObservable.clear();
  58361. };
  58362. /**
  58363. * Clones the particle system.
  58364. * @param name The name of the cloned object
  58365. * @param newEmitter The new emitter to use
  58366. * @returns the cloned particle system
  58367. */
  58368. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58369. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58370. BABYLON.Tools.DeepCopy(this, result);
  58371. if (newEmitter === undefined) {
  58372. newEmitter = this.emitter;
  58373. }
  58374. result.emitter = newEmitter;
  58375. if (this.particleTexture) {
  58376. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58377. }
  58378. return result;
  58379. };
  58380. /**
  58381. * Serializes the particle system to a JSON object.
  58382. * @returns the JSON object
  58383. */
  58384. GPUParticleSystem.prototype.serialize = function () {
  58385. var serializationObject = {};
  58386. serializationObject.name = this.name;
  58387. serializationObject.id = this.id;
  58388. // Emitter
  58389. if (this.emitter.position) {
  58390. var emitterMesh = this.emitter;
  58391. serializationObject.emitterId = emitterMesh.id;
  58392. }
  58393. else {
  58394. var emitterPosition = this.emitter;
  58395. serializationObject.emitter = emitterPosition.asArray();
  58396. }
  58397. serializationObject.capacity = this.getCapacity();
  58398. if (this.particleTexture) {
  58399. serializationObject.textureName = this.particleTexture.name;
  58400. }
  58401. // Animations
  58402. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58403. // Particle system
  58404. serializationObject.activeParticleCount = this.activeParticleCount;
  58405. serializationObject.randomTextureSize = this._randomTextureSize;
  58406. serializationObject.minSize = this.minSize;
  58407. serializationObject.maxSize = this.maxSize;
  58408. serializationObject.minEmitPower = this.minEmitPower;
  58409. serializationObject.maxEmitPower = this.maxEmitPower;
  58410. serializationObject.minLifeTime = this.minLifeTime;
  58411. serializationObject.maxLifeTime = this.maxLifeTime;
  58412. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58413. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58414. serializationObject.emitRate = this.emitRate;
  58415. serializationObject.gravity = this.gravity.asArray();
  58416. serializationObject.color1 = this.color1.asArray();
  58417. serializationObject.color2 = this.color2.asArray();
  58418. serializationObject.colorDead = this.colorDead.asArray();
  58419. serializationObject.updateSpeed = this.updateSpeed;
  58420. serializationObject.targetStopDuration = this.targetStopDuration;
  58421. serializationObject.blendMode = this.blendMode;
  58422. // Emitter
  58423. if (this.particleEmitterType) {
  58424. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58425. }
  58426. return serializationObject;
  58427. };
  58428. /**
  58429. * Parses a JSON object to create a GPU particle system.
  58430. * @param parsedParticleSystem The JSON object to parse
  58431. * @param scene The scene to create the particle system in
  58432. * @param rootUrl The root url to use to load external dependencies like texture
  58433. * @returns the parsed GPU particle system
  58434. */
  58435. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58436. var name = parsedParticleSystem.name;
  58437. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58438. if (parsedParticleSystem.id) {
  58439. particleSystem.id = parsedParticleSystem.id;
  58440. }
  58441. // Texture
  58442. if (parsedParticleSystem.textureName) {
  58443. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58444. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58445. }
  58446. // Emitter
  58447. if (parsedParticleSystem.emitterId) {
  58448. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58449. }
  58450. else {
  58451. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58452. }
  58453. // Animations
  58454. if (parsedParticleSystem.animations) {
  58455. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58456. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58457. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58458. }
  58459. }
  58460. // Particle system
  58461. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58462. particleSystem.minSize = parsedParticleSystem.minSize;
  58463. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58464. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58465. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58466. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58467. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58468. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58469. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58470. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58471. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58472. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58473. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58474. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58475. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58476. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58477. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58478. // Emitter
  58479. if (parsedParticleSystem.particleEmitterType) {
  58480. var emitterType = void 0;
  58481. switch (parsedParticleSystem.particleEmitterType.type) {
  58482. case "SphereEmitter":
  58483. emitterType = new BABYLON.SphereParticleEmitter();
  58484. break;
  58485. case "SphereDirectedParticleEmitter":
  58486. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58487. break;
  58488. case "ConeEmitter":
  58489. emitterType = new BABYLON.ConeParticleEmitter();
  58490. break;
  58491. case "BoxEmitter":
  58492. default:
  58493. emitterType = new BABYLON.BoxParticleEmitter();
  58494. break;
  58495. }
  58496. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58497. particleSystem.particleEmitterType = emitterType;
  58498. }
  58499. return particleSystem;
  58500. };
  58501. return GPUParticleSystem;
  58502. }());
  58503. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58504. })(BABYLON || (BABYLON = {}));
  58505. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58506. var BABYLON;
  58507. (function (BABYLON) {
  58508. /**
  58509. * Represents one particle of a solid particle system.
  58510. */
  58511. var SolidParticle = /** @class */ (function () {
  58512. /**
  58513. * Creates a Solid Particle object.
  58514. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58515. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58516. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58517. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58518. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58519. * @param shapeId (integer) is the model shape identifier in the SPS.
  58520. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58521. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58522. */
  58523. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58524. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58525. /**
  58526. * particle global index
  58527. */
  58528. this.idx = 0;
  58529. /**
  58530. * The color of the particle
  58531. */
  58532. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58533. /**
  58534. * The world space position of the particle.
  58535. */
  58536. this.position = BABYLON.Vector3.Zero();
  58537. /**
  58538. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58539. */
  58540. this.rotation = BABYLON.Vector3.Zero();
  58541. /**
  58542. * The scaling of the particle.
  58543. */
  58544. this.scaling = BABYLON.Vector3.One();
  58545. /**
  58546. * The uvs of the particle.
  58547. */
  58548. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58549. /**
  58550. * The current speed of the particle.
  58551. */
  58552. this.velocity = BABYLON.Vector3.Zero();
  58553. /**
  58554. * The pivot point in the particle local space.
  58555. */
  58556. this.pivot = BABYLON.Vector3.Zero();
  58557. /**
  58558. * Must the particle be translated from its pivot point in its local space ?
  58559. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58560. * Default : false
  58561. */
  58562. this.translateFromPivot = false;
  58563. /**
  58564. * Is the particle active or not ?
  58565. */
  58566. this.alive = true;
  58567. /**
  58568. * Is the particle visible or not ?
  58569. */
  58570. this.isVisible = true;
  58571. /**
  58572. * Index of this particle in the global "positions" array (Internal use)
  58573. */
  58574. this._pos = 0;
  58575. /**
  58576. * Index of this particle in the global "indices" array (Internal use)
  58577. */
  58578. this._ind = 0;
  58579. /**
  58580. * ModelShape id of this particle
  58581. */
  58582. this.shapeId = 0;
  58583. /**
  58584. * Index of the particle in its shape id (Internal use)
  58585. */
  58586. this.idxInShape = 0;
  58587. /**
  58588. * Still set as invisible in order to skip useless computations (Internal use)
  58589. */
  58590. this._stillInvisible = false;
  58591. /**
  58592. * Last computed particle rotation matrix
  58593. */
  58594. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58595. /**
  58596. * Parent particle Id, if any.
  58597. * Default null.
  58598. */
  58599. this.parentId = null;
  58600. /**
  58601. * Internal global position in the SPS.
  58602. */
  58603. this._globalPosition = BABYLON.Vector3.Zero();
  58604. this.idx = particleIndex;
  58605. this._pos = positionIndex;
  58606. this._ind = indiceIndex;
  58607. this._model = model;
  58608. this.shapeId = shapeId;
  58609. this.idxInShape = idxInShape;
  58610. this._sps = sps;
  58611. if (modelBoundingInfo) {
  58612. this._modelBoundingInfo = modelBoundingInfo;
  58613. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58614. }
  58615. }
  58616. Object.defineProperty(SolidParticle.prototype, "scale", {
  58617. /**
  58618. * Legacy support, changed scale to scaling
  58619. */
  58620. get: function () {
  58621. return this.scaling;
  58622. },
  58623. /**
  58624. * Legacy support, changed scale to scaling
  58625. */
  58626. set: function (scale) {
  58627. this.scaling = scale;
  58628. },
  58629. enumerable: true,
  58630. configurable: true
  58631. });
  58632. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58633. /**
  58634. * Legacy support, changed quaternion to rotationQuaternion
  58635. */
  58636. get: function () {
  58637. return this.rotationQuaternion;
  58638. },
  58639. /**
  58640. * Legacy support, changed quaternion to rotationQuaternion
  58641. */
  58642. set: function (q) {
  58643. this.rotationQuaternion = q;
  58644. },
  58645. enumerable: true,
  58646. configurable: true
  58647. });
  58648. /**
  58649. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58650. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58651. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58652. * @returns true if it intersects
  58653. */
  58654. SolidParticle.prototype.intersectsMesh = function (target) {
  58655. if (!this._boundingInfo || !target._boundingInfo) {
  58656. return false;
  58657. }
  58658. if (this._sps._bSphereOnly) {
  58659. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58660. }
  58661. return this._boundingInfo.intersects(target._boundingInfo, false);
  58662. };
  58663. return SolidParticle;
  58664. }());
  58665. BABYLON.SolidParticle = SolidParticle;
  58666. /**
  58667. * Represents the shape of the model used by one particle of a solid particle system.
  58668. * SPS internal tool, don't use it manually.
  58669. */
  58670. var ModelShape = /** @class */ (function () {
  58671. /**
  58672. * 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.
  58673. * SPS internal tool, don't use it manually.
  58674. * @hidden
  58675. */
  58676. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58677. /**
  58678. * length of the shape in the model indices array (internal use)
  58679. */
  58680. this._indicesLength = 0;
  58681. this.shapeID = id;
  58682. this._shape = shape;
  58683. this._indicesLength = indicesLength;
  58684. this._shapeUV = shapeUV;
  58685. this._positionFunction = posFunction;
  58686. this._vertexFunction = vtxFunction;
  58687. }
  58688. return ModelShape;
  58689. }());
  58690. BABYLON.ModelShape = ModelShape;
  58691. /**
  58692. * Represents a Depth Sorted Particle in the solid particle system.
  58693. */
  58694. var DepthSortedParticle = /** @class */ (function () {
  58695. function DepthSortedParticle() {
  58696. /**
  58697. * Index of the particle in the "indices" array
  58698. */
  58699. this.ind = 0;
  58700. /**
  58701. * Length of the particle shape in the "indices" array
  58702. */
  58703. this.indicesLength = 0;
  58704. /**
  58705. * Squared distance from the particle to the camera
  58706. */
  58707. this.sqDistance = 0.0;
  58708. }
  58709. return DepthSortedParticle;
  58710. }());
  58711. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58712. })(BABYLON || (BABYLON = {}));
  58713. //# sourceMappingURL=babylon.solidParticle.js.map
  58714. var BABYLON;
  58715. (function (BABYLON) {
  58716. /**
  58717. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58718. *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.
  58719. * The SPS is also a particle system. It provides some methods to manage the particles.
  58720. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58721. *
  58722. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58723. */
  58724. var SolidParticleSystem = /** @class */ (function () {
  58725. /**
  58726. * Creates a SPS (Solid Particle System) object.
  58727. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58728. * @param scene (Scene) is the scene in which the SPS is added.
  58729. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58730. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58731. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58732. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58733. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58734. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58735. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58736. */
  58737. function SolidParticleSystem(name, scene, options) {
  58738. /**
  58739. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58740. * Example : var p = SPS.particles[i];
  58741. */
  58742. this.particles = new Array();
  58743. /**
  58744. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58745. */
  58746. this.nbParticles = 0;
  58747. /**
  58748. * If the particles must ever face the camera (default false). Useful for planar particles.
  58749. */
  58750. this.billboard = false;
  58751. /**
  58752. * Recompute normals when adding a shape
  58753. */
  58754. this.recomputeNormals = true;
  58755. /**
  58756. * This a counter ofr your own usage. It's not set by any SPS functions.
  58757. */
  58758. this.counter = 0;
  58759. /**
  58760. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58761. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58762. */
  58763. this.vars = {};
  58764. /**
  58765. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58766. */
  58767. this._bSphereOnly = false;
  58768. /**
  58769. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58770. */
  58771. this._bSphereRadiusFactor = 1.0;
  58772. this._positions = new Array();
  58773. this._indices = new Array();
  58774. this._normals = new Array();
  58775. this._colors = new Array();
  58776. this._uvs = new Array();
  58777. this._index = 0; // indices index
  58778. this._updatable = true;
  58779. this._pickable = false;
  58780. this._isVisibilityBoxLocked = false;
  58781. this._alwaysVisible = false;
  58782. this._depthSort = false;
  58783. this._shapeCounter = 0;
  58784. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58785. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58786. this._computeParticleColor = true;
  58787. this._computeParticleTexture = true;
  58788. this._computeParticleRotation = true;
  58789. this._computeParticleVertex = false;
  58790. this._computeBoundingBox = false;
  58791. this._depthSortParticles = true;
  58792. this._cam_axisZ = BABYLON.Vector3.Zero();
  58793. this._cam_axisY = BABYLON.Vector3.Zero();
  58794. this._cam_axisX = BABYLON.Vector3.Zero();
  58795. this._axisZ = BABYLON.Axis.Z;
  58796. this._camDir = BABYLON.Vector3.Zero();
  58797. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58798. this._rotMatrix = new BABYLON.Matrix();
  58799. this._invertMatrix = new BABYLON.Matrix();
  58800. this._rotated = BABYLON.Vector3.Zero();
  58801. this._quaternion = new BABYLON.Quaternion();
  58802. this._vertex = BABYLON.Vector3.Zero();
  58803. this._normal = BABYLON.Vector3.Zero();
  58804. this._yaw = 0.0;
  58805. this._pitch = 0.0;
  58806. this._roll = 0.0;
  58807. this._halfroll = 0.0;
  58808. this._halfpitch = 0.0;
  58809. this._halfyaw = 0.0;
  58810. this._sinRoll = 0.0;
  58811. this._cosRoll = 0.0;
  58812. this._sinPitch = 0.0;
  58813. this._cosPitch = 0.0;
  58814. this._sinYaw = 0.0;
  58815. this._cosYaw = 0.0;
  58816. this._mustUnrotateFixedNormals = false;
  58817. this._minimum = BABYLON.Vector3.Zero();
  58818. this._maximum = BABYLON.Vector3.Zero();
  58819. this._minBbox = BABYLON.Vector3.Zero();
  58820. this._maxBbox = BABYLON.Vector3.Zero();
  58821. this._particlesIntersect = false;
  58822. this._depthSortFunction = function (p1, p2) {
  58823. return (p2.sqDistance - p1.sqDistance);
  58824. };
  58825. this._needs32Bits = false;
  58826. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58827. this._scaledPivot = BABYLON.Vector3.Zero();
  58828. this._particleHasParent = false;
  58829. this.name = name;
  58830. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58831. this._camera = scene.activeCamera;
  58832. this._pickable = options ? options.isPickable : false;
  58833. this._depthSort = options ? options.enableDepthSort : false;
  58834. this._particlesIntersect = options ? options.particleIntersection : false;
  58835. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58836. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58837. if (options && options.updatable !== undefined) {
  58838. this._updatable = options.updatable;
  58839. }
  58840. else {
  58841. this._updatable = true;
  58842. }
  58843. if (this._pickable) {
  58844. this.pickedParticles = [];
  58845. }
  58846. if (this._depthSort) {
  58847. this.depthSortedParticles = [];
  58848. }
  58849. }
  58850. /**
  58851. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58852. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58853. * @returns the created mesh
  58854. */
  58855. SolidParticleSystem.prototype.buildMesh = function () {
  58856. if (this.nbParticles === 0) {
  58857. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58858. this.addShape(triangle, 1);
  58859. triangle.dispose();
  58860. }
  58861. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58862. this._positions32 = new Float32Array(this._positions);
  58863. this._uvs32 = new Float32Array(this._uvs);
  58864. this._colors32 = new Float32Array(this._colors);
  58865. if (this.recomputeNormals) {
  58866. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58867. }
  58868. this._normals32 = new Float32Array(this._normals);
  58869. this._fixedNormal32 = new Float32Array(this._normals);
  58870. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58871. this._unrotateFixedNormals();
  58872. }
  58873. var vertexData = new BABYLON.VertexData();
  58874. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58875. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58876. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58877. if (this._uvs32.length > 0) {
  58878. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58879. }
  58880. if (this._colors32.length > 0) {
  58881. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58882. }
  58883. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58884. vertexData.applyToMesh(mesh, this._updatable);
  58885. this.mesh = mesh;
  58886. this.mesh.isPickable = this._pickable;
  58887. // free memory
  58888. if (!this._depthSort) {
  58889. this._indices = null;
  58890. }
  58891. this._positions = null;
  58892. this._normals = null;
  58893. this._uvs = null;
  58894. this._colors = null;
  58895. if (!this._updatable) {
  58896. this.particles.length = 0;
  58897. }
  58898. return mesh;
  58899. };
  58900. /**
  58901. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58902. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58903. * Thus the particles generated from `digest()` have their property `position` set yet.
  58904. * @param mesh ( Mesh ) is the mesh to be digested
  58905. * @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
  58906. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58907. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58908. * @returns the current SPS
  58909. */
  58910. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58911. var size = (options && options.facetNb) || 1;
  58912. var number = (options && options.number) || 0;
  58913. var delta = (options && options.delta) || 0;
  58914. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58915. var meshInd = mesh.getIndices();
  58916. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58917. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58918. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58919. var f = 0; // facet counter
  58920. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58921. // compute size from number
  58922. if (number) {
  58923. number = (number > totalFacets) ? totalFacets : number;
  58924. size = Math.round(totalFacets / number);
  58925. delta = 0;
  58926. }
  58927. else {
  58928. size = (size > totalFacets) ? totalFacets : size;
  58929. }
  58930. var facetPos = []; // submesh positions
  58931. var facetInd = []; // submesh indices
  58932. var facetUV = []; // submesh UV
  58933. var facetCol = []; // submesh colors
  58934. var barycenter = BABYLON.Vector3.Zero();
  58935. var sizeO = size;
  58936. while (f < totalFacets) {
  58937. size = sizeO + Math.floor((1 + delta) * Math.random());
  58938. if (f > totalFacets - size) {
  58939. size = totalFacets - f;
  58940. }
  58941. // reset temp arrays
  58942. facetPos.length = 0;
  58943. facetInd.length = 0;
  58944. facetUV.length = 0;
  58945. facetCol.length = 0;
  58946. // iterate over "size" facets
  58947. var fi = 0;
  58948. for (var j = f * 3; j < (f + size) * 3; j++) {
  58949. facetInd.push(fi);
  58950. var i = meshInd[j];
  58951. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58952. if (meshUV) {
  58953. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58954. }
  58955. if (meshCol) {
  58956. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58957. }
  58958. fi++;
  58959. }
  58960. // create a model shape for each single particle
  58961. var idx = this.nbParticles;
  58962. var shape = this._posToShape(facetPos);
  58963. var shapeUV = this._uvsToShapeUV(facetUV);
  58964. // compute the barycenter of the shape
  58965. var v;
  58966. for (v = 0; v < shape.length; v++) {
  58967. barycenter.addInPlace(shape[v]);
  58968. }
  58969. barycenter.scaleInPlace(1 / shape.length);
  58970. // shift the shape from its barycenter to the origin
  58971. for (v = 0; v < shape.length; v++) {
  58972. shape[v].subtractInPlace(barycenter);
  58973. }
  58974. var bInfo;
  58975. if (this._particlesIntersect) {
  58976. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58977. }
  58978. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58979. // add the particle in the SPS
  58980. var currentPos = this._positions.length;
  58981. var currentInd = this._indices.length;
  58982. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58983. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58984. // initialize the particle position
  58985. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58986. this._index += shape.length;
  58987. idx++;
  58988. this.nbParticles++;
  58989. this._shapeCounter++;
  58990. f += size;
  58991. }
  58992. return this;
  58993. };
  58994. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58995. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58996. var index = 0;
  58997. var idx = 0;
  58998. for (var p = 0; p < this.particles.length; p++) {
  58999. this._particle = this.particles[p];
  59000. this._shape = this._particle._model._shape;
  59001. if (this._particle.rotationQuaternion) {
  59002. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59003. }
  59004. else {
  59005. this._yaw = this._particle.rotation.y;
  59006. this._pitch = this._particle.rotation.x;
  59007. this._roll = this._particle.rotation.z;
  59008. this._quaternionRotationYPR();
  59009. }
  59010. this._quaternionToRotationMatrix();
  59011. this._rotMatrix.invertToRef(this._invertMatrix);
  59012. for (var pt = 0; pt < this._shape.length; pt++) {
  59013. idx = index + pt * 3;
  59014. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  59015. this._fixedNormal32[idx] = this._normal.x;
  59016. this._fixedNormal32[idx + 1] = this._normal.y;
  59017. this._fixedNormal32[idx + 2] = this._normal.z;
  59018. }
  59019. index = idx + 3;
  59020. }
  59021. };
  59022. //reset copy
  59023. SolidParticleSystem.prototype._resetCopy = function () {
  59024. this._copy.position.x = 0;
  59025. this._copy.position.y = 0;
  59026. this._copy.position.z = 0;
  59027. this._copy.rotation.x = 0;
  59028. this._copy.rotation.y = 0;
  59029. this._copy.rotation.z = 0;
  59030. this._copy.rotationQuaternion = null;
  59031. this._copy.scaling.x = 1.0;
  59032. this._copy.scaling.y = 1.0;
  59033. this._copy.scaling.z = 1.0;
  59034. this._copy.uvs.x = 0;
  59035. this._copy.uvs.y = 0;
  59036. this._copy.uvs.z = 1.0;
  59037. this._copy.uvs.w = 1.0;
  59038. this._copy.color = null;
  59039. this._copy.translateFromPivot = false;
  59040. };
  59041. // _meshBuilder : inserts the shape model in the global SPS mesh
  59042. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  59043. var i;
  59044. var u = 0;
  59045. var c = 0;
  59046. var n = 0;
  59047. this._resetCopy();
  59048. if (options && options.positionFunction) { // call to custom positionFunction
  59049. options.positionFunction(this._copy, idx, idxInShape);
  59050. this._mustUnrotateFixedNormals = true;
  59051. }
  59052. if (this._copy.rotationQuaternion) {
  59053. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59054. }
  59055. else {
  59056. this._yaw = this._copy.rotation.y;
  59057. this._pitch = this._copy.rotation.x;
  59058. this._roll = this._copy.rotation.z;
  59059. this._quaternionRotationYPR();
  59060. }
  59061. this._quaternionToRotationMatrix();
  59062. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  59063. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  59064. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  59065. if (this._copy.translateFromPivot) {
  59066. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59067. }
  59068. else {
  59069. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59070. }
  59071. for (i = 0; i < shape.length; i++) {
  59072. this._vertex.x = shape[i].x;
  59073. this._vertex.y = shape[i].y;
  59074. this._vertex.z = shape[i].z;
  59075. if (options && options.vertexFunction) {
  59076. options.vertexFunction(this._copy, this._vertex, i);
  59077. }
  59078. this._vertex.x *= this._copy.scaling.x;
  59079. this._vertex.y *= this._copy.scaling.y;
  59080. this._vertex.z *= this._copy.scaling.z;
  59081. this._vertex.x -= this._scaledPivot.x;
  59082. this._vertex.y -= this._scaledPivot.y;
  59083. this._vertex.z -= this._scaledPivot.z;
  59084. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59085. this._rotated.addInPlace(this._pivotBackTranslation);
  59086. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  59087. if (meshUV) {
  59088. 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);
  59089. u += 2;
  59090. }
  59091. if (this._copy.color) {
  59092. this._color = this._copy.color;
  59093. }
  59094. else if (meshCol && meshCol[c] !== undefined) {
  59095. this._color.r = meshCol[c];
  59096. this._color.g = meshCol[c + 1];
  59097. this._color.b = meshCol[c + 2];
  59098. this._color.a = meshCol[c + 3];
  59099. }
  59100. else {
  59101. this._color.r = 1.0;
  59102. this._color.g = 1.0;
  59103. this._color.b = 1.0;
  59104. this._color.a = 1.0;
  59105. }
  59106. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  59107. c += 4;
  59108. if (!this.recomputeNormals && meshNor) {
  59109. this._normal.x = meshNor[n];
  59110. this._normal.y = meshNor[n + 1];
  59111. this._normal.z = meshNor[n + 2];
  59112. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  59113. normals.push(this._normal.x, this._normal.y, this._normal.z);
  59114. n += 3;
  59115. }
  59116. }
  59117. for (i = 0; i < meshInd.length; i++) {
  59118. var current_ind = p + meshInd[i];
  59119. indices.push(current_ind);
  59120. if (current_ind > 65535) {
  59121. this._needs32Bits = true;
  59122. }
  59123. }
  59124. if (this._pickable) {
  59125. var nbfaces = meshInd.length / 3;
  59126. for (i = 0; i < nbfaces; i++) {
  59127. this.pickedParticles.push({ idx: idx, faceId: i });
  59128. }
  59129. }
  59130. if (this._depthSort) {
  59131. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  59132. }
  59133. return this._copy;
  59134. };
  59135. // returns a shape array from positions array
  59136. SolidParticleSystem.prototype._posToShape = function (positions) {
  59137. var shape = [];
  59138. for (var i = 0; i < positions.length; i += 3) {
  59139. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  59140. }
  59141. return shape;
  59142. };
  59143. // returns a shapeUV array from a Vector4 uvs
  59144. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  59145. var shapeUV = [];
  59146. if (uvs) {
  59147. for (var i = 0; i < uvs.length; i++)
  59148. shapeUV.push(uvs[i]);
  59149. }
  59150. return shapeUV;
  59151. };
  59152. // adds a new particle object in the particles array
  59153. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  59154. if (bInfo === void 0) { bInfo = null; }
  59155. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  59156. this.particles.push(sp);
  59157. return sp;
  59158. };
  59159. /**
  59160. * Adds some particles to the SPS from the model shape. Returns the shape id.
  59161. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  59162. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  59163. * @param nb (positive integer) the number of particles to be created from this model
  59164. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  59165. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  59166. * @returns the number of shapes in the system
  59167. */
  59168. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  59169. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59170. var meshInd = mesh.getIndices();
  59171. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59172. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59173. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59174. var bbInfo;
  59175. if (this._particlesIntersect) {
  59176. bbInfo = mesh.getBoundingInfo();
  59177. }
  59178. var shape = this._posToShape(meshPos);
  59179. var shapeUV = this._uvsToShapeUV(meshUV);
  59180. var posfunc = options ? options.positionFunction : null;
  59181. var vtxfunc = options ? options.vertexFunction : null;
  59182. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  59183. // particles
  59184. var sp;
  59185. var currentCopy;
  59186. var idx = this.nbParticles;
  59187. for (var i = 0; i < nb; i++) {
  59188. var currentPos = this._positions.length;
  59189. var currentInd = this._indices.length;
  59190. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  59191. if (this._updatable) {
  59192. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  59193. sp.position.copyFrom(currentCopy.position);
  59194. sp.rotation.copyFrom(currentCopy.rotation);
  59195. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  59196. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  59197. }
  59198. if (currentCopy.color && sp.color) {
  59199. sp.color.copyFrom(currentCopy.color);
  59200. }
  59201. sp.scaling.copyFrom(currentCopy.scaling);
  59202. sp.uvs.copyFrom(currentCopy.uvs);
  59203. }
  59204. this._index += shape.length;
  59205. idx++;
  59206. }
  59207. this.nbParticles += nb;
  59208. this._shapeCounter++;
  59209. return this._shapeCounter - 1;
  59210. };
  59211. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59212. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59213. this._resetCopy();
  59214. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59215. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59216. }
  59217. if (this._copy.rotationQuaternion) {
  59218. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59219. }
  59220. else {
  59221. this._yaw = this._copy.rotation.y;
  59222. this._pitch = this._copy.rotation.x;
  59223. this._roll = this._copy.rotation.z;
  59224. this._quaternionRotationYPR();
  59225. }
  59226. this._quaternionToRotationMatrix();
  59227. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59228. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59229. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59230. if (this._copy.translateFromPivot) {
  59231. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59232. }
  59233. else {
  59234. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59235. }
  59236. this._shape = particle._model._shape;
  59237. for (var pt = 0; pt < this._shape.length; pt++) {
  59238. this._vertex.x = this._shape[pt].x;
  59239. this._vertex.y = this._shape[pt].y;
  59240. this._vertex.z = this._shape[pt].z;
  59241. if (particle._model._vertexFunction) {
  59242. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59243. }
  59244. this._vertex.x *= this._copy.scaling.x;
  59245. this._vertex.y *= this._copy.scaling.y;
  59246. this._vertex.z *= this._copy.scaling.z;
  59247. this._vertex.x -= this._scaledPivot.x;
  59248. this._vertex.y -= this._scaledPivot.y;
  59249. this._vertex.z -= this._scaledPivot.z;
  59250. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59251. this._rotated.addInPlace(this._pivotBackTranslation);
  59252. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59253. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59254. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59255. }
  59256. particle.position.x = 0.0;
  59257. particle.position.y = 0.0;
  59258. particle.position.z = 0.0;
  59259. particle.rotation.x = 0.0;
  59260. particle.rotation.y = 0.0;
  59261. particle.rotation.z = 0.0;
  59262. particle.rotationQuaternion = null;
  59263. particle.scaling.x = 1.0;
  59264. particle.scaling.y = 1.0;
  59265. particle.scaling.z = 1.0;
  59266. particle.uvs.x = 0.0;
  59267. particle.uvs.y = 0.0;
  59268. particle.uvs.z = 1.0;
  59269. particle.uvs.w = 1.0;
  59270. particle.pivot.x = 0.0;
  59271. particle.pivot.y = 0.0;
  59272. particle.pivot.z = 0.0;
  59273. particle.translateFromPivot = false;
  59274. particle.parentId = null;
  59275. };
  59276. /**
  59277. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59278. * @returns the SPS.
  59279. */
  59280. SolidParticleSystem.prototype.rebuildMesh = function () {
  59281. for (var p = 0; p < this.particles.length; p++) {
  59282. this._rebuildParticle(this.particles[p]);
  59283. }
  59284. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59285. return this;
  59286. };
  59287. /**
  59288. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59289. * This method calls `updateParticle()` for each particle of the SPS.
  59290. * For an animated SPS, it is usually called within the render loop.
  59291. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59292. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59293. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59294. * @returns the SPS.
  59295. */
  59296. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59297. if (start === void 0) { start = 0; }
  59298. if (end === void 0) { end = this.nbParticles - 1; }
  59299. if (update === void 0) { update = true; }
  59300. if (!this._updatable) {
  59301. return this;
  59302. }
  59303. // custom beforeUpdate
  59304. this.beforeUpdateParticles(start, end, update);
  59305. this._cam_axisX.x = 1.0;
  59306. this._cam_axisX.y = 0.0;
  59307. this._cam_axisX.z = 0.0;
  59308. this._cam_axisY.x = 0.0;
  59309. this._cam_axisY.y = 1.0;
  59310. this._cam_axisY.z = 0.0;
  59311. this._cam_axisZ.x = 0.0;
  59312. this._cam_axisZ.y = 0.0;
  59313. this._cam_axisZ.z = 1.0;
  59314. // cases when the World Matrix is to be computed first
  59315. if (this.billboard || this._depthSort) {
  59316. this.mesh.computeWorldMatrix(true);
  59317. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59318. }
  59319. // if the particles will always face the camera
  59320. if (this.billboard) {
  59321. // compute the camera position and un-rotate it by the current mesh rotation
  59322. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59323. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59324. this._cam_axisZ.normalize();
  59325. // same for camera up vector extracted from the cam view matrix
  59326. var view = this._camera.getViewMatrix(true);
  59327. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59328. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59329. this._cam_axisY.normalize();
  59330. this._cam_axisX.normalize();
  59331. }
  59332. // if depthSort, compute the camera global position in the mesh local system
  59333. if (this._depthSort) {
  59334. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59335. }
  59336. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59337. var idx = 0; // current position index in the global array positions32
  59338. var index = 0; // position start index in the global array positions32 of the current particle
  59339. var colidx = 0; // current color index in the global array colors32
  59340. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59341. var uvidx = 0; // current uv index in the global array uvs32
  59342. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59343. var pt = 0; // current index in the particle model shape
  59344. if (this.mesh.isFacetDataEnabled) {
  59345. this._computeBoundingBox = true;
  59346. }
  59347. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59348. if (this._computeBoundingBox) {
  59349. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59350. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59351. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59352. }
  59353. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59354. if (this.mesh._boundingInfo) {
  59355. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59356. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59357. }
  59358. }
  59359. }
  59360. // particle loop
  59361. index = this.particles[start]._pos;
  59362. var vpos = (index / 3) | 0;
  59363. colorIndex = vpos * 4;
  59364. uvIndex = vpos * 2;
  59365. for (var p = start; p <= end; p++) {
  59366. this._particle = this.particles[p];
  59367. this._shape = this._particle._model._shape;
  59368. this._shapeUV = this._particle._model._shapeUV;
  59369. // call to custom user function to update the particle properties
  59370. this.updateParticle(this._particle);
  59371. // camera-particle distance for depth sorting
  59372. if (this._depthSort && this._depthSortParticles) {
  59373. var dsp = this.depthSortedParticles[p];
  59374. dsp.ind = this._particle._ind;
  59375. dsp.indicesLength = this._particle._model._indicesLength;
  59376. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59377. }
  59378. // skip the computations for inactive or already invisible particles
  59379. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59380. // increment indexes for the next particle
  59381. pt = this._shape.length;
  59382. index += pt * 3;
  59383. colorIndex += pt * 4;
  59384. uvIndex += pt * 2;
  59385. continue;
  59386. }
  59387. if (this._particle.isVisible) {
  59388. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59389. this._particleHasParent = (this._particle.parentId !== null);
  59390. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59391. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59392. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59393. // particle rotation matrix
  59394. if (this.billboard) {
  59395. this._particle.rotation.x = 0.0;
  59396. this._particle.rotation.y = 0.0;
  59397. }
  59398. if (this._computeParticleRotation || this.billboard) {
  59399. if (this._particle.rotationQuaternion) {
  59400. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59401. }
  59402. else {
  59403. this._yaw = this._particle.rotation.y;
  59404. this._pitch = this._particle.rotation.x;
  59405. this._roll = this._particle.rotation.z;
  59406. this._quaternionRotationYPR();
  59407. }
  59408. this._quaternionToRotationMatrix();
  59409. }
  59410. if (this._particleHasParent) {
  59411. this._parent = this.particles[this._particle.parentId];
  59412. 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];
  59413. 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];
  59414. 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];
  59415. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59416. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59417. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59418. if (this._computeParticleRotation || this.billboard) {
  59419. 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];
  59420. 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];
  59421. 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];
  59422. 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];
  59423. 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];
  59424. 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];
  59425. 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];
  59426. 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];
  59427. 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];
  59428. }
  59429. }
  59430. else {
  59431. this._particle._globalPosition.x = this._particle.position.x;
  59432. this._particle._globalPosition.y = this._particle.position.y;
  59433. this._particle._globalPosition.z = this._particle.position.z;
  59434. if (this._computeParticleRotation || this.billboard) {
  59435. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59436. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59437. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59438. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59439. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59440. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59441. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59442. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59443. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59444. }
  59445. }
  59446. if (this._particle.translateFromPivot) {
  59447. this._pivotBackTranslation.x = 0.0;
  59448. this._pivotBackTranslation.y = 0.0;
  59449. this._pivotBackTranslation.z = 0.0;
  59450. }
  59451. else {
  59452. this._pivotBackTranslation.x = this._scaledPivot.x;
  59453. this._pivotBackTranslation.y = this._scaledPivot.y;
  59454. this._pivotBackTranslation.z = this._scaledPivot.z;
  59455. }
  59456. // particle vertex loop
  59457. for (pt = 0; pt < this._shape.length; pt++) {
  59458. idx = index + pt * 3;
  59459. colidx = colorIndex + pt * 4;
  59460. uvidx = uvIndex + pt * 2;
  59461. this._vertex.x = this._shape[pt].x;
  59462. this._vertex.y = this._shape[pt].y;
  59463. this._vertex.z = this._shape[pt].z;
  59464. if (this._computeParticleVertex) {
  59465. this.updateParticleVertex(this._particle, this._vertex, pt);
  59466. }
  59467. // positions
  59468. this._vertex.x *= this._particle.scaling.x;
  59469. this._vertex.y *= this._particle.scaling.y;
  59470. this._vertex.z *= this._particle.scaling.z;
  59471. this._vertex.x -= this._scaledPivot.x;
  59472. this._vertex.y -= this._scaledPivot.y;
  59473. this._vertex.z -= this._scaledPivot.z;
  59474. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59475. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59476. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59477. this._rotated.x += this._pivotBackTranslation.x;
  59478. this._rotated.y += this._pivotBackTranslation.y;
  59479. this._rotated.z += this._pivotBackTranslation.z;
  59480. 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;
  59481. 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;
  59482. 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;
  59483. if (this._computeBoundingBox) {
  59484. if (this._positions32[idx] < this._minimum.x) {
  59485. this._minimum.x = this._positions32[idx];
  59486. }
  59487. if (this._positions32[idx] > this._maximum.x) {
  59488. this._maximum.x = this._positions32[idx];
  59489. }
  59490. if (this._positions32[idx + 1] < this._minimum.y) {
  59491. this._minimum.y = this._positions32[idx + 1];
  59492. }
  59493. if (this._positions32[idx + 1] > this._maximum.y) {
  59494. this._maximum.y = this._positions32[idx + 1];
  59495. }
  59496. if (this._positions32[idx + 2] < this._minimum.z) {
  59497. this._minimum.z = this._positions32[idx + 2];
  59498. }
  59499. if (this._positions32[idx + 2] > this._maximum.z) {
  59500. this._maximum.z = this._positions32[idx + 2];
  59501. }
  59502. }
  59503. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59504. if (!this._computeParticleVertex) {
  59505. this._normal.x = this._fixedNormal32[idx];
  59506. this._normal.y = this._fixedNormal32[idx + 1];
  59507. this._normal.z = this._fixedNormal32[idx + 2];
  59508. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59509. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59510. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59511. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59512. 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;
  59513. 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;
  59514. }
  59515. if (this._computeParticleColor && this._particle.color) {
  59516. this._colors32[colidx] = this._particle.color.r;
  59517. this._colors32[colidx + 1] = this._particle.color.g;
  59518. this._colors32[colidx + 2] = this._particle.color.b;
  59519. this._colors32[colidx + 3] = this._particle.color.a;
  59520. }
  59521. if (this._computeParticleTexture) {
  59522. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59523. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59524. }
  59525. }
  59526. }
  59527. // particle just set invisible : scaled to zero and positioned at the origin
  59528. else {
  59529. this._particle._stillInvisible = true; // mark the particle as invisible
  59530. for (pt = 0; pt < this._shape.length; pt++) {
  59531. idx = index + pt * 3;
  59532. colidx = colorIndex + pt * 4;
  59533. uvidx = uvIndex + pt * 2;
  59534. this._positions32[idx] = 0.0;
  59535. this._positions32[idx + 1] = 0.0;
  59536. this._positions32[idx + 2] = 0.0;
  59537. this._normals32[idx] = 0.0;
  59538. this._normals32[idx + 1] = 0.0;
  59539. this._normals32[idx + 2] = 0.0;
  59540. if (this._computeParticleColor && this._particle.color) {
  59541. this._colors32[colidx] = this._particle.color.r;
  59542. this._colors32[colidx + 1] = this._particle.color.g;
  59543. this._colors32[colidx + 2] = this._particle.color.b;
  59544. this._colors32[colidx + 3] = this._particle.color.a;
  59545. }
  59546. if (this._computeParticleTexture) {
  59547. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59548. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59549. }
  59550. }
  59551. }
  59552. // if the particle intersections must be computed : update the bbInfo
  59553. if (this._particlesIntersect) {
  59554. var bInfo = this._particle._boundingInfo;
  59555. var bBox = bInfo.boundingBox;
  59556. var bSphere = bInfo.boundingSphere;
  59557. if (!this._bSphereOnly) {
  59558. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59559. for (var b = 0; b < bBox.vectors.length; b++) {
  59560. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59561. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59562. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59563. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59564. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59565. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59566. 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;
  59567. 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;
  59568. 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;
  59569. }
  59570. bBox._update(this.mesh._worldMatrix);
  59571. }
  59572. // place and scale the particle bouding sphere in the SPS local system, then update it
  59573. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59574. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59575. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59576. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59577. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59578. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59579. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59580. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59581. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59582. 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));
  59583. bSphere._update(this.mesh._worldMatrix);
  59584. }
  59585. // increment indexes for the next particle
  59586. index = idx + 3;
  59587. colorIndex = colidx + 4;
  59588. uvIndex = uvidx + 2;
  59589. }
  59590. // if the VBO must be updated
  59591. if (update) {
  59592. if (this._computeParticleColor) {
  59593. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59594. }
  59595. if (this._computeParticleTexture) {
  59596. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59597. }
  59598. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59599. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59600. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59601. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59602. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59603. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59604. for (var i = 0; i < this._normals32.length; i++) {
  59605. this._fixedNormal32[i] = this._normals32[i];
  59606. }
  59607. }
  59608. if (!this.mesh.areNormalsFrozen) {
  59609. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59610. }
  59611. }
  59612. if (this._depthSort && this._depthSortParticles) {
  59613. this.depthSortedParticles.sort(this._depthSortFunction);
  59614. var dspl = this.depthSortedParticles.length;
  59615. var sorted = 0;
  59616. var lind = 0;
  59617. var sind = 0;
  59618. var sid = 0;
  59619. for (sorted = 0; sorted < dspl; sorted++) {
  59620. lind = this.depthSortedParticles[sorted].indicesLength;
  59621. sind = this.depthSortedParticles[sorted].ind;
  59622. for (var i = 0; i < lind; i++) {
  59623. this._indices32[sid] = this._indices[sind + i];
  59624. sid++;
  59625. }
  59626. }
  59627. this.mesh.updateIndices(this._indices32);
  59628. }
  59629. }
  59630. if (this._computeBoundingBox) {
  59631. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59632. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59633. }
  59634. this.afterUpdateParticles(start, end, update);
  59635. return this;
  59636. };
  59637. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59638. this._halfroll = this._roll * 0.5;
  59639. this._halfpitch = this._pitch * 0.5;
  59640. this._halfyaw = this._yaw * 0.5;
  59641. this._sinRoll = Math.sin(this._halfroll);
  59642. this._cosRoll = Math.cos(this._halfroll);
  59643. this._sinPitch = Math.sin(this._halfpitch);
  59644. this._cosPitch = Math.cos(this._halfpitch);
  59645. this._sinYaw = Math.sin(this._halfyaw);
  59646. this._cosYaw = Math.cos(this._halfyaw);
  59647. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59648. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59649. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59650. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59651. };
  59652. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59653. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59654. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59655. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59656. this._rotMatrix.m[3] = 0;
  59657. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59658. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59659. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59660. this._rotMatrix.m[7] = 0;
  59661. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59662. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59663. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59664. this._rotMatrix.m[11] = 0;
  59665. this._rotMatrix.m[12] = 0;
  59666. this._rotMatrix.m[13] = 0;
  59667. this._rotMatrix.m[14] = 0;
  59668. this._rotMatrix.m[15] = 1.0;
  59669. };
  59670. /**
  59671. * Disposes the SPS.
  59672. */
  59673. SolidParticleSystem.prototype.dispose = function () {
  59674. this.mesh.dispose();
  59675. this.vars = null;
  59676. // drop references to internal big arrays for the GC
  59677. this._positions = null;
  59678. this._indices = null;
  59679. this._normals = null;
  59680. this._uvs = null;
  59681. this._colors = null;
  59682. this._indices32 = null;
  59683. this._positions32 = null;
  59684. this._normals32 = null;
  59685. this._fixedNormal32 = null;
  59686. this._uvs32 = null;
  59687. this._colors32 = null;
  59688. this.pickedParticles = null;
  59689. };
  59690. /**
  59691. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59692. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59693. * @returns the SPS.
  59694. */
  59695. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59696. if (!this._isVisibilityBoxLocked) {
  59697. this.mesh.refreshBoundingInfo();
  59698. }
  59699. return this;
  59700. };
  59701. /**
  59702. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59703. * @param size the size (float) of the visibility box
  59704. * note : this doesn't lock the SPS mesh bounding box.
  59705. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59706. */
  59707. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59708. var vis = size / 2;
  59709. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59710. };
  59711. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59712. /**
  59713. * Gets whether the SPS as always visible or not
  59714. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59715. */
  59716. get: function () {
  59717. return this._alwaysVisible;
  59718. },
  59719. /**
  59720. * Sets the SPS as always visible or not
  59721. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59722. */
  59723. set: function (val) {
  59724. this._alwaysVisible = val;
  59725. this.mesh.alwaysSelectAsActiveMesh = val;
  59726. },
  59727. enumerable: true,
  59728. configurable: true
  59729. });
  59730. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59731. /**
  59732. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59733. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59734. */
  59735. get: function () {
  59736. return this._isVisibilityBoxLocked;
  59737. },
  59738. /**
  59739. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59740. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59741. */
  59742. set: function (val) {
  59743. this._isVisibilityBoxLocked = val;
  59744. var boundingInfo = this.mesh.getBoundingInfo();
  59745. boundingInfo.isLocked = val;
  59746. },
  59747. enumerable: true,
  59748. configurable: true
  59749. });
  59750. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59751. /**
  59752. * Gets if `setParticles()` computes the particle rotations or not.
  59753. * Default value : true. The SPS is faster when it's set to false.
  59754. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59755. */
  59756. get: function () {
  59757. return this._computeParticleRotation;
  59758. },
  59759. /**
  59760. * Tells to `setParticles()` to compute the particle rotations or not.
  59761. * Default value : true. The SPS is faster when it's set to false.
  59762. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59763. */
  59764. set: function (val) {
  59765. this._computeParticleRotation = val;
  59766. },
  59767. enumerable: true,
  59768. configurable: true
  59769. });
  59770. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59771. /**
  59772. * Gets if `setParticles()` computes the particle colors or not.
  59773. * Default value : true. The SPS is faster when it's set to false.
  59774. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59775. */
  59776. get: function () {
  59777. return this._computeParticleColor;
  59778. },
  59779. /**
  59780. * Tells to `setParticles()` to compute the particle colors or not.
  59781. * Default value : true. The SPS is faster when it's set to false.
  59782. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59783. */
  59784. set: function (val) {
  59785. this._computeParticleColor = val;
  59786. },
  59787. enumerable: true,
  59788. configurable: true
  59789. });
  59790. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59791. /**
  59792. * Gets if `setParticles()` computes the particle textures or not.
  59793. * Default value : true. The SPS is faster when it's set to false.
  59794. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59795. */
  59796. get: function () {
  59797. return this._computeParticleTexture;
  59798. },
  59799. set: function (val) {
  59800. this._computeParticleTexture = val;
  59801. },
  59802. enumerable: true,
  59803. configurable: true
  59804. });
  59805. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59806. /**
  59807. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59808. * Default value : false. The SPS is faster when it's set to false.
  59809. * Note : the particle custom vertex positions aren't stored values.
  59810. */
  59811. get: function () {
  59812. return this._computeParticleVertex;
  59813. },
  59814. /**
  59815. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59816. * Default value : false. The SPS is faster when it's set to false.
  59817. * Note : the particle custom vertex positions aren't stored values.
  59818. */
  59819. set: function (val) {
  59820. this._computeParticleVertex = val;
  59821. },
  59822. enumerable: true,
  59823. configurable: true
  59824. });
  59825. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59826. /**
  59827. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59828. */
  59829. get: function () {
  59830. return this._computeBoundingBox;
  59831. },
  59832. /**
  59833. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59834. */
  59835. set: function (val) {
  59836. this._computeBoundingBox = val;
  59837. },
  59838. enumerable: true,
  59839. configurable: true
  59840. });
  59841. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59842. /**
  59843. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59844. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59845. * Default : `true`
  59846. */
  59847. get: function () {
  59848. return this._depthSortParticles;
  59849. },
  59850. /**
  59851. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59852. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59853. * Default : `true`
  59854. */
  59855. set: function (val) {
  59856. this._depthSortParticles = val;
  59857. },
  59858. enumerable: true,
  59859. configurable: true
  59860. });
  59861. // =======================================================================
  59862. // Particle behavior logic
  59863. // these following methods may be overwritten by the user to fit his needs
  59864. /**
  59865. * This function does nothing. It may be overwritten to set all the particle first values.
  59866. * The SPS doesn't call this function, you may have to call it by your own.
  59867. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59868. */
  59869. SolidParticleSystem.prototype.initParticles = function () {
  59870. };
  59871. /**
  59872. * This function does nothing. It may be overwritten to recycle a particle.
  59873. * The SPS doesn't call this function, you may have to call it by your own.
  59874. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59875. * @param particle The particle to recycle
  59876. * @returns the recycled particle
  59877. */
  59878. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59879. return particle;
  59880. };
  59881. /**
  59882. * Updates a particle : this function should be overwritten by the user.
  59883. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59884. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59885. * @example : just set a particle position or velocity and recycle conditions
  59886. * @param particle The particle to update
  59887. * @returns the updated particle
  59888. */
  59889. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59890. return particle;
  59891. };
  59892. /**
  59893. * Updates a vertex of a particle : it can be overwritten by the user.
  59894. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59895. * @param particle the current particle
  59896. * @param vertex the current index of the current particle
  59897. * @param pt the index of the current vertex in the particle shape
  59898. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59899. * @example : just set a vertex particle position
  59900. * @returns the updated vertex
  59901. */
  59902. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59903. return vertex;
  59904. };
  59905. /**
  59906. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59907. * This does nothing and may be overwritten by the user.
  59908. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59909. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59910. * @param update the boolean update value actually passed to setParticles()
  59911. */
  59912. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59913. };
  59914. /**
  59915. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59916. * This will be passed three parameters.
  59917. * This does nothing and may be overwritten by the user.
  59918. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59919. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59920. * @param update the boolean update value actually passed to setParticles()
  59921. */
  59922. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59923. };
  59924. return SolidParticleSystem;
  59925. }());
  59926. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59927. })(BABYLON || (BABYLON = {}));
  59928. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59929. var BABYLON;
  59930. (function (BABYLON) {
  59931. var ShaderMaterial = /** @class */ (function (_super) {
  59932. __extends(ShaderMaterial, _super);
  59933. function ShaderMaterial(name, scene, shaderPath, options) {
  59934. var _this = _super.call(this, name, scene) || this;
  59935. _this._textures = {};
  59936. _this._textureArrays = {};
  59937. _this._floats = {};
  59938. _this._ints = {};
  59939. _this._floatsArrays = {};
  59940. _this._colors3 = {};
  59941. _this._colors3Arrays = {};
  59942. _this._colors4 = {};
  59943. _this._vectors2 = {};
  59944. _this._vectors3 = {};
  59945. _this._vectors4 = {};
  59946. _this._matrices = {};
  59947. _this._matrices3x3 = {};
  59948. _this._matrices2x2 = {};
  59949. _this._vectors2Arrays = {};
  59950. _this._vectors3Arrays = {};
  59951. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59952. _this._shaderPath = shaderPath;
  59953. options.needAlphaBlending = options.needAlphaBlending || false;
  59954. options.needAlphaTesting = options.needAlphaTesting || false;
  59955. options.attributes = options.attributes || ["position", "normal", "uv"];
  59956. options.uniforms = options.uniforms || ["worldViewProjection"];
  59957. options.uniformBuffers = options.uniformBuffers || [];
  59958. options.samplers = options.samplers || [];
  59959. options.defines = options.defines || [];
  59960. _this._options = options;
  59961. return _this;
  59962. }
  59963. ShaderMaterial.prototype.getClassName = function () {
  59964. return "ShaderMaterial";
  59965. };
  59966. ShaderMaterial.prototype.needAlphaBlending = function () {
  59967. return this._options.needAlphaBlending;
  59968. };
  59969. ShaderMaterial.prototype.needAlphaTesting = function () {
  59970. return this._options.needAlphaTesting;
  59971. };
  59972. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59973. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59974. this._options.uniforms.push(uniformName);
  59975. }
  59976. };
  59977. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59978. if (this._options.samplers.indexOf(name) === -1) {
  59979. this._options.samplers.push(name);
  59980. }
  59981. this._textures[name] = texture;
  59982. return this;
  59983. };
  59984. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59985. if (this._options.samplers.indexOf(name) === -1) {
  59986. this._options.samplers.push(name);
  59987. }
  59988. this._checkUniform(name);
  59989. this._textureArrays[name] = textures;
  59990. return this;
  59991. };
  59992. ShaderMaterial.prototype.setFloat = function (name, value) {
  59993. this._checkUniform(name);
  59994. this._floats[name] = value;
  59995. return this;
  59996. };
  59997. ShaderMaterial.prototype.setInt = function (name, value) {
  59998. this._checkUniform(name);
  59999. this._ints[name] = value;
  60000. return this;
  60001. };
  60002. ShaderMaterial.prototype.setFloats = function (name, value) {
  60003. this._checkUniform(name);
  60004. this._floatsArrays[name] = value;
  60005. return this;
  60006. };
  60007. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60008. this._checkUniform(name);
  60009. this._colors3[name] = value;
  60010. return this;
  60011. };
  60012. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60013. this._checkUniform(name);
  60014. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60015. color.toArray(arr, arr.length);
  60016. return arr;
  60017. }, []);
  60018. return this;
  60019. };
  60020. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60021. this._checkUniform(name);
  60022. this._colors4[name] = value;
  60023. return this;
  60024. };
  60025. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60026. this._checkUniform(name);
  60027. this._vectors2[name] = value;
  60028. return this;
  60029. };
  60030. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60031. this._checkUniform(name);
  60032. this._vectors3[name] = value;
  60033. return this;
  60034. };
  60035. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60036. this._checkUniform(name);
  60037. this._vectors4[name] = value;
  60038. return this;
  60039. };
  60040. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60041. this._checkUniform(name);
  60042. this._matrices[name] = value;
  60043. return this;
  60044. };
  60045. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60046. this._checkUniform(name);
  60047. this._matrices3x3[name] = value;
  60048. return this;
  60049. };
  60050. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60051. this._checkUniform(name);
  60052. this._matrices2x2[name] = value;
  60053. return this;
  60054. };
  60055. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60056. this._checkUniform(name);
  60057. this._vectors2Arrays[name] = value;
  60058. return this;
  60059. };
  60060. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60061. this._checkUniform(name);
  60062. this._vectors3Arrays[name] = value;
  60063. return this;
  60064. };
  60065. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60066. if (!mesh) {
  60067. return true;
  60068. }
  60069. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60070. return false;
  60071. }
  60072. return false;
  60073. };
  60074. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60075. var scene = this.getScene();
  60076. var engine = scene.getEngine();
  60077. if (!this.checkReadyOnEveryCall) {
  60078. if (this._renderId === scene.getRenderId()) {
  60079. if (this._checkCache(scene, mesh, useInstances)) {
  60080. return true;
  60081. }
  60082. }
  60083. }
  60084. // Instances
  60085. var defines = [];
  60086. var attribs = [];
  60087. var fallbacks = new BABYLON.EffectFallbacks();
  60088. if (useInstances) {
  60089. defines.push("#define INSTANCES");
  60090. }
  60091. for (var index = 0; index < this._options.defines.length; index++) {
  60092. defines.push(this._options.defines[index]);
  60093. }
  60094. for (var index = 0; index < this._options.attributes.length; index++) {
  60095. attribs.push(this._options.attributes[index]);
  60096. }
  60097. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60098. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60099. defines.push("#define VERTEXCOLOR");
  60100. }
  60101. // Bones
  60102. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60103. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60104. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60105. if (mesh.numBoneInfluencers > 4) {
  60106. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60107. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60108. }
  60109. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60110. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60111. fallbacks.addCPUSkinningFallback(0, mesh);
  60112. if (this._options.uniforms.indexOf("mBones") === -1) {
  60113. this._options.uniforms.push("mBones");
  60114. }
  60115. }
  60116. else {
  60117. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60118. }
  60119. // Textures
  60120. for (var name in this._textures) {
  60121. if (!this._textures[name].isReady()) {
  60122. return false;
  60123. }
  60124. }
  60125. // Alpha test
  60126. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60127. defines.push("#define ALPHATEST");
  60128. }
  60129. var previousEffect = this._effect;
  60130. var join = defines.join("\n");
  60131. this._effect = engine.createEffect(this._shaderPath, {
  60132. attributes: attribs,
  60133. uniformsNames: this._options.uniforms,
  60134. uniformBuffersNames: this._options.uniformBuffers,
  60135. samplers: this._options.samplers,
  60136. defines: join,
  60137. fallbacks: fallbacks,
  60138. onCompiled: this.onCompiled,
  60139. onError: this.onError
  60140. }, engine);
  60141. if (!this._effect.isReady()) {
  60142. return false;
  60143. }
  60144. if (previousEffect !== this._effect) {
  60145. scene.resetCachedMaterial();
  60146. }
  60147. this._renderId = scene.getRenderId();
  60148. return true;
  60149. };
  60150. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60151. var scene = this.getScene();
  60152. if (!this._effect) {
  60153. return;
  60154. }
  60155. if (this._options.uniforms.indexOf("world") !== -1) {
  60156. this._effect.setMatrix("world", world);
  60157. }
  60158. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60159. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60160. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60161. }
  60162. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60163. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60164. }
  60165. };
  60166. ShaderMaterial.prototype.bind = function (world, mesh) {
  60167. // Std values
  60168. this.bindOnlyWorldMatrix(world);
  60169. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60170. if (this._options.uniforms.indexOf("view") !== -1) {
  60171. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60172. }
  60173. if (this._options.uniforms.indexOf("projection") !== -1) {
  60174. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60175. }
  60176. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60177. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60178. }
  60179. // Bones
  60180. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60181. var name;
  60182. // Texture
  60183. for (name in this._textures) {
  60184. this._effect.setTexture(name, this._textures[name]);
  60185. }
  60186. // Texture arrays
  60187. for (name in this._textureArrays) {
  60188. this._effect.setTextureArray(name, this._textureArrays[name]);
  60189. }
  60190. // Int
  60191. for (name in this._ints) {
  60192. this._effect.setInt(name, this._ints[name]);
  60193. }
  60194. // Float
  60195. for (name in this._floats) {
  60196. this._effect.setFloat(name, this._floats[name]);
  60197. }
  60198. // Floats
  60199. for (name in this._floatsArrays) {
  60200. this._effect.setArray(name, this._floatsArrays[name]);
  60201. }
  60202. // Color3
  60203. for (name in this._colors3) {
  60204. this._effect.setColor3(name, this._colors3[name]);
  60205. }
  60206. for (name in this._colors3Arrays) {
  60207. this._effect.setArray3(name, this._colors3Arrays[name]);
  60208. }
  60209. // Color4
  60210. for (name in this._colors4) {
  60211. var color = this._colors4[name];
  60212. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60213. }
  60214. // Vector2
  60215. for (name in this._vectors2) {
  60216. this._effect.setVector2(name, this._vectors2[name]);
  60217. }
  60218. // Vector3
  60219. for (name in this._vectors3) {
  60220. this._effect.setVector3(name, this._vectors3[name]);
  60221. }
  60222. // Vector4
  60223. for (name in this._vectors4) {
  60224. this._effect.setVector4(name, this._vectors4[name]);
  60225. }
  60226. // Matrix
  60227. for (name in this._matrices) {
  60228. this._effect.setMatrix(name, this._matrices[name]);
  60229. }
  60230. // Matrix 3x3
  60231. for (name in this._matrices3x3) {
  60232. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60233. }
  60234. // Matrix 2x2
  60235. for (name in this._matrices2x2) {
  60236. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60237. }
  60238. // Vector2Array
  60239. for (name in this._vectors2Arrays) {
  60240. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60241. }
  60242. // Vector3Array
  60243. for (name in this._vectors3Arrays) {
  60244. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60245. }
  60246. }
  60247. this._afterBind(mesh);
  60248. };
  60249. ShaderMaterial.prototype.getActiveTextures = function () {
  60250. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60251. for (var name in this._textures) {
  60252. activeTextures.push(this._textures[name]);
  60253. }
  60254. for (var name in this._textureArrays) {
  60255. var array = this._textureArrays[name];
  60256. for (var index = 0; index < array.length; index++) {
  60257. activeTextures.push(array[index]);
  60258. }
  60259. }
  60260. return activeTextures;
  60261. };
  60262. ShaderMaterial.prototype.hasTexture = function (texture) {
  60263. if (_super.prototype.hasTexture.call(this, texture)) {
  60264. return true;
  60265. }
  60266. for (var name in this._textures) {
  60267. if (this._textures[name] === texture) {
  60268. return true;
  60269. }
  60270. }
  60271. for (var name in this._textureArrays) {
  60272. var array = this._textureArrays[name];
  60273. for (var index = 0; index < array.length; index++) {
  60274. if (array[index] === texture) {
  60275. return true;
  60276. }
  60277. }
  60278. }
  60279. return false;
  60280. };
  60281. ShaderMaterial.prototype.clone = function (name) {
  60282. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60283. return newShaderMaterial;
  60284. };
  60285. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60286. if (forceDisposeTextures) {
  60287. var name;
  60288. for (name in this._textures) {
  60289. this._textures[name].dispose();
  60290. }
  60291. for (name in this._textureArrays) {
  60292. var array = this._textureArrays[name];
  60293. for (var index = 0; index < array.length; index++) {
  60294. array[index].dispose();
  60295. }
  60296. }
  60297. }
  60298. this._textures = {};
  60299. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60300. };
  60301. ShaderMaterial.prototype.serialize = function () {
  60302. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60303. serializationObject.customType = "BABYLON.ShaderMaterial";
  60304. serializationObject.options = this._options;
  60305. serializationObject.shaderPath = this._shaderPath;
  60306. var name;
  60307. // Texture
  60308. serializationObject.textures = {};
  60309. for (name in this._textures) {
  60310. serializationObject.textures[name] = this._textures[name].serialize();
  60311. }
  60312. // Texture arrays
  60313. serializationObject.textureArrays = {};
  60314. for (name in this._textureArrays) {
  60315. serializationObject.textureArrays[name] = [];
  60316. var array = this._textureArrays[name];
  60317. for (var index = 0; index < array.length; index++) {
  60318. serializationObject.textureArrays[name].push(array[index].serialize());
  60319. }
  60320. }
  60321. // Float
  60322. serializationObject.floats = {};
  60323. for (name in this._floats) {
  60324. serializationObject.floats[name] = this._floats[name];
  60325. }
  60326. // Float s
  60327. serializationObject.FloatArrays = {};
  60328. for (name in this._floatsArrays) {
  60329. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60330. }
  60331. // Color3
  60332. serializationObject.colors3 = {};
  60333. for (name in this._colors3) {
  60334. serializationObject.colors3[name] = this._colors3[name].asArray();
  60335. }
  60336. // Color3 array
  60337. serializationObject.colors3Arrays = {};
  60338. for (name in this._colors3Arrays) {
  60339. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60340. }
  60341. // Color4
  60342. serializationObject.colors4 = {};
  60343. for (name in this._colors4) {
  60344. serializationObject.colors4[name] = this._colors4[name].asArray();
  60345. }
  60346. // Vector2
  60347. serializationObject.vectors2 = {};
  60348. for (name in this._vectors2) {
  60349. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60350. }
  60351. // Vector3
  60352. serializationObject.vectors3 = {};
  60353. for (name in this._vectors3) {
  60354. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60355. }
  60356. // Vector4
  60357. serializationObject.vectors4 = {};
  60358. for (name in this._vectors4) {
  60359. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60360. }
  60361. // Matrix
  60362. serializationObject.matrices = {};
  60363. for (name in this._matrices) {
  60364. serializationObject.matrices[name] = this._matrices[name].asArray();
  60365. }
  60366. // Matrix 3x3
  60367. serializationObject.matrices3x3 = {};
  60368. for (name in this._matrices3x3) {
  60369. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60370. }
  60371. // Matrix 2x2
  60372. serializationObject.matrices2x2 = {};
  60373. for (name in this._matrices2x2) {
  60374. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60375. }
  60376. // Vector2Array
  60377. serializationObject.vectors2Arrays = {};
  60378. for (name in this._vectors2Arrays) {
  60379. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60380. }
  60381. // Vector3Array
  60382. serializationObject.vectors3Arrays = {};
  60383. for (name in this._vectors3Arrays) {
  60384. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60385. }
  60386. return serializationObject;
  60387. };
  60388. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60389. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60390. var name;
  60391. // Texture
  60392. for (name in source.textures) {
  60393. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60394. }
  60395. // Texture arrays
  60396. for (name in source.textureArrays) {
  60397. var array = source.textureArrays[name];
  60398. var textureArray = new Array();
  60399. for (var index = 0; index < array.length; index++) {
  60400. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60401. }
  60402. material.setTextureArray(name, textureArray);
  60403. }
  60404. // Float
  60405. for (name in source.floats) {
  60406. material.setFloat(name, source.floats[name]);
  60407. }
  60408. // Float s
  60409. for (name in source.floatsArrays) {
  60410. material.setFloats(name, source.floatsArrays[name]);
  60411. }
  60412. // Color3
  60413. for (name in source.colors3) {
  60414. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60415. }
  60416. // Color3 arrays
  60417. for (name in source.colors3Arrays) {
  60418. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60419. if (i % 3 === 0) {
  60420. arr.push([num]);
  60421. }
  60422. else {
  60423. arr[arr.length - 1].push(num);
  60424. }
  60425. return arr;
  60426. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60427. material.setColor3Array(name, colors);
  60428. }
  60429. // Color4
  60430. for (name in source.colors4) {
  60431. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60432. }
  60433. // Vector2
  60434. for (name in source.vectors2) {
  60435. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60436. }
  60437. // Vector3
  60438. for (name in source.vectors3) {
  60439. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60440. }
  60441. // Vector4
  60442. for (name in source.vectors4) {
  60443. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60444. }
  60445. // Matrix
  60446. for (name in source.matrices) {
  60447. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60448. }
  60449. // Matrix 3x3
  60450. for (name in source.matrices3x3) {
  60451. material.setMatrix3x3(name, source.matrices3x3[name]);
  60452. }
  60453. // Matrix 2x2
  60454. for (name in source.matrices2x2) {
  60455. material.setMatrix2x2(name, source.matrices2x2[name]);
  60456. }
  60457. // Vector2Array
  60458. for (name in source.vectors2Arrays) {
  60459. material.setArray2(name, source.vectors2Arrays[name]);
  60460. }
  60461. // Vector3Array
  60462. for (name in source.vectors3Arrays) {
  60463. material.setArray3(name, source.vectors3Arrays[name]);
  60464. }
  60465. return material;
  60466. };
  60467. return ShaderMaterial;
  60468. }(BABYLON.Material));
  60469. BABYLON.ShaderMaterial = ShaderMaterial;
  60470. })(BABYLON || (BABYLON = {}));
  60471. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60472. var BABYLON;
  60473. (function (BABYLON) {
  60474. var GroundMesh = /** @class */ (function (_super) {
  60475. __extends(GroundMesh, _super);
  60476. function GroundMesh(name, scene) {
  60477. var _this = _super.call(this, name, scene) || this;
  60478. _this.generateOctree = false;
  60479. return _this;
  60480. }
  60481. GroundMesh.prototype.getClassName = function () {
  60482. return "GroundMesh";
  60483. };
  60484. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60485. get: function () {
  60486. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60487. },
  60488. enumerable: true,
  60489. configurable: true
  60490. });
  60491. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60492. get: function () {
  60493. return this._subdivisionsX;
  60494. },
  60495. enumerable: true,
  60496. configurable: true
  60497. });
  60498. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60499. get: function () {
  60500. return this._subdivisionsY;
  60501. },
  60502. enumerable: true,
  60503. configurable: true
  60504. });
  60505. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60506. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60507. this._subdivisionsX = chunksCount;
  60508. this._subdivisionsY = chunksCount;
  60509. this.subdivide(chunksCount);
  60510. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60511. };
  60512. /**
  60513. * Returns a height (y) value in the Worl system :
  60514. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60515. * Returns the ground y position if (x, z) are outside the ground surface.
  60516. */
  60517. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60518. var world = this.getWorldMatrix();
  60519. var invMat = BABYLON.Tmp.Matrix[5];
  60520. world.invertToRef(invMat);
  60521. var tmpVect = BABYLON.Tmp.Vector3[8];
  60522. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60523. x = tmpVect.x;
  60524. z = tmpVect.z;
  60525. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60526. return this.position.y;
  60527. }
  60528. if (!this._heightQuads || this._heightQuads.length == 0) {
  60529. this._initHeightQuads();
  60530. this._computeHeightQuads();
  60531. }
  60532. var facet = this._getFacetAt(x, z);
  60533. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60534. // return y in the World system
  60535. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60536. return tmpVect.y;
  60537. };
  60538. /**
  60539. * Returns a normalized vector (Vector3) orthogonal to the ground
  60540. * at the ground coordinates (x, z) expressed in the World system.
  60541. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60542. */
  60543. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60544. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60545. this.getNormalAtCoordinatesToRef(x, z, normal);
  60546. return normal;
  60547. };
  60548. /**
  60549. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60550. * at the ground coordinates (x, z) expressed in the World system.
  60551. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60552. * Returns the GroundMesh.
  60553. */
  60554. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60555. var world = this.getWorldMatrix();
  60556. var tmpMat = BABYLON.Tmp.Matrix[5];
  60557. world.invertToRef(tmpMat);
  60558. var tmpVect = BABYLON.Tmp.Vector3[8];
  60559. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60560. x = tmpVect.x;
  60561. z = tmpVect.z;
  60562. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60563. return this;
  60564. }
  60565. if (!this._heightQuads || this._heightQuads.length == 0) {
  60566. this._initHeightQuads();
  60567. this._computeHeightQuads();
  60568. }
  60569. var facet = this._getFacetAt(x, z);
  60570. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60571. return this;
  60572. };
  60573. /**
  60574. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60575. * if the ground has been updated.
  60576. * This can be used in the render loop.
  60577. * Returns the GroundMesh.
  60578. */
  60579. GroundMesh.prototype.updateCoordinateHeights = function () {
  60580. if (!this._heightQuads || this._heightQuads.length == 0) {
  60581. this._initHeightQuads();
  60582. }
  60583. this._computeHeightQuads();
  60584. return this;
  60585. };
  60586. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60587. GroundMesh.prototype._getFacetAt = function (x, z) {
  60588. // retrieve col and row from x, z coordinates in the ground local system
  60589. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60590. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60591. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60592. var facet;
  60593. if (z < quad.slope.x * x + quad.slope.y) {
  60594. facet = quad.facet1;
  60595. }
  60596. else {
  60597. facet = quad.facet2;
  60598. }
  60599. return facet;
  60600. };
  60601. // Creates and populates the heightMap array with "facet" elements :
  60602. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60603. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60604. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60605. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60606. // Returns the GroundMesh.
  60607. GroundMesh.prototype._initHeightQuads = function () {
  60608. var subdivisionsX = this._subdivisionsX;
  60609. var subdivisionsY = this._subdivisionsY;
  60610. this._heightQuads = new Array();
  60611. for (var row = 0; row < subdivisionsY; row++) {
  60612. for (var col = 0; col < subdivisionsX; col++) {
  60613. 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) };
  60614. this._heightQuads[row * subdivisionsX + col] = quad;
  60615. }
  60616. }
  60617. return this;
  60618. };
  60619. // Compute each quad element values and update the the heightMap array :
  60620. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60621. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60622. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60623. // Returns the GroundMesh.
  60624. GroundMesh.prototype._computeHeightQuads = function () {
  60625. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60626. if (!positions) {
  60627. return this;
  60628. }
  60629. var v1 = BABYLON.Tmp.Vector3[3];
  60630. var v2 = BABYLON.Tmp.Vector3[2];
  60631. var v3 = BABYLON.Tmp.Vector3[1];
  60632. var v4 = BABYLON.Tmp.Vector3[0];
  60633. var v1v2 = BABYLON.Tmp.Vector3[4];
  60634. var v1v3 = BABYLON.Tmp.Vector3[5];
  60635. var v1v4 = BABYLON.Tmp.Vector3[6];
  60636. var norm1 = BABYLON.Tmp.Vector3[7];
  60637. var norm2 = BABYLON.Tmp.Vector3[8];
  60638. var i = 0;
  60639. var j = 0;
  60640. var k = 0;
  60641. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60642. var h = 0;
  60643. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60644. var d2 = 0;
  60645. var subdivisionsX = this._subdivisionsX;
  60646. var subdivisionsY = this._subdivisionsY;
  60647. for (var row = 0; row < subdivisionsY; row++) {
  60648. for (var col = 0; col < subdivisionsX; col++) {
  60649. i = col * 3;
  60650. j = row * (subdivisionsX + 1) * 3;
  60651. k = (row + 1) * (subdivisionsX + 1) * 3;
  60652. v1.x = positions[j + i];
  60653. v1.y = positions[j + i + 1];
  60654. v1.z = positions[j + i + 2];
  60655. v2.x = positions[j + i + 3];
  60656. v2.y = positions[j + i + 4];
  60657. v2.z = positions[j + i + 5];
  60658. v3.x = positions[k + i];
  60659. v3.y = positions[k + i + 1];
  60660. v3.z = positions[k + i + 2];
  60661. v4.x = positions[k + i + 3];
  60662. v4.y = positions[k + i + 4];
  60663. v4.z = positions[k + i + 5];
  60664. // 2D slope V1V4
  60665. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60666. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60667. // facet equations :
  60668. // we compute each facet normal vector
  60669. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60670. // we compute the value d by applying the equation to v1 which belongs to the plane
  60671. // then we store the facet equation in a Vector4
  60672. v2.subtractToRef(v1, v1v2);
  60673. v3.subtractToRef(v1, v1v3);
  60674. v4.subtractToRef(v1, v1v4);
  60675. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60676. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60677. norm1.normalize();
  60678. norm2.normalize();
  60679. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60680. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60681. var quad = this._heightQuads[row * subdivisionsX + col];
  60682. quad.slope.copyFromFloats(cd, h);
  60683. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60684. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60685. }
  60686. }
  60687. return this;
  60688. };
  60689. GroundMesh.prototype.serialize = function (serializationObject) {
  60690. _super.prototype.serialize.call(this, serializationObject);
  60691. serializationObject.subdivisionsX = this._subdivisionsX;
  60692. serializationObject.subdivisionsY = this._subdivisionsY;
  60693. serializationObject.minX = this._minX;
  60694. serializationObject.maxX = this._maxX;
  60695. serializationObject.minZ = this._minZ;
  60696. serializationObject.maxZ = this._maxZ;
  60697. serializationObject.width = this._width;
  60698. serializationObject.height = this._height;
  60699. };
  60700. GroundMesh.Parse = function (parsedMesh, scene) {
  60701. var result = new GroundMesh(parsedMesh.name, scene);
  60702. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60703. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60704. result._minX = parsedMesh.minX;
  60705. result._maxX = parsedMesh.maxX;
  60706. result._minZ = parsedMesh.minZ;
  60707. result._maxZ = parsedMesh.maxZ;
  60708. result._width = parsedMesh.width;
  60709. result._height = parsedMesh.height;
  60710. return result;
  60711. };
  60712. return GroundMesh;
  60713. }(BABYLON.Mesh));
  60714. BABYLON.GroundMesh = GroundMesh;
  60715. })(BABYLON || (BABYLON = {}));
  60716. //# sourceMappingURL=babylon.groundMesh.js.map
  60717. var BABYLON;
  60718. (function (BABYLON) {
  60719. /**
  60720. * Creates an instance based on a source mesh.
  60721. */
  60722. var InstancedMesh = /** @class */ (function (_super) {
  60723. __extends(InstancedMesh, _super);
  60724. function InstancedMesh(name, source) {
  60725. var _this = _super.call(this, name, source.getScene()) || this;
  60726. source.instances.push(_this);
  60727. _this._sourceMesh = source;
  60728. _this.position.copyFrom(source.position);
  60729. _this.rotation.copyFrom(source.rotation);
  60730. _this.scaling.copyFrom(source.scaling);
  60731. if (source.rotationQuaternion) {
  60732. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60733. }
  60734. _this.infiniteDistance = source.infiniteDistance;
  60735. _this.setPivotMatrix(source.getPivotMatrix());
  60736. _this.refreshBoundingInfo();
  60737. _this._syncSubMeshes();
  60738. return _this;
  60739. }
  60740. /**
  60741. * Returns the string "InstancedMesh".
  60742. */
  60743. InstancedMesh.prototype.getClassName = function () {
  60744. return "InstancedMesh";
  60745. };
  60746. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60747. // Methods
  60748. get: function () {
  60749. return this._sourceMesh.receiveShadows;
  60750. },
  60751. enumerable: true,
  60752. configurable: true
  60753. });
  60754. Object.defineProperty(InstancedMesh.prototype, "material", {
  60755. get: function () {
  60756. return this._sourceMesh.material;
  60757. },
  60758. enumerable: true,
  60759. configurable: true
  60760. });
  60761. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60762. get: function () {
  60763. return this._sourceMesh.visibility;
  60764. },
  60765. enumerable: true,
  60766. configurable: true
  60767. });
  60768. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60769. get: function () {
  60770. return this._sourceMesh.skeleton;
  60771. },
  60772. enumerable: true,
  60773. configurable: true
  60774. });
  60775. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60776. get: function () {
  60777. return this._sourceMesh.renderingGroupId;
  60778. },
  60779. set: function (value) {
  60780. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60781. return;
  60782. }
  60783. //no-op with warning
  60784. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60785. },
  60786. enumerable: true,
  60787. configurable: true
  60788. });
  60789. /**
  60790. * Returns the total number of vertices (integer).
  60791. */
  60792. InstancedMesh.prototype.getTotalVertices = function () {
  60793. return this._sourceMesh.getTotalVertices();
  60794. };
  60795. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60796. get: function () {
  60797. return this._sourceMesh;
  60798. },
  60799. enumerable: true,
  60800. configurable: true
  60801. });
  60802. /**
  60803. * Is this node ready to be used/rendered
  60804. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60805. * @return {boolean} is it ready
  60806. */
  60807. InstancedMesh.prototype.isReady = function (completeCheck) {
  60808. if (completeCheck === void 0) { completeCheck = false; }
  60809. return this._sourceMesh.isReady(completeCheck, true);
  60810. };
  60811. /**
  60812. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60813. */
  60814. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60815. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60816. };
  60817. /**
  60818. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60819. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60820. * The `data` are either a numeric array either a Float32Array.
  60821. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60822. * 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).
  60823. * Note that a new underlying VertexBuffer object is created each call.
  60824. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60825. *
  60826. * Possible `kind` values :
  60827. * - BABYLON.VertexBuffer.PositionKind
  60828. * - BABYLON.VertexBuffer.UVKind
  60829. * - BABYLON.VertexBuffer.UV2Kind
  60830. * - BABYLON.VertexBuffer.UV3Kind
  60831. * - BABYLON.VertexBuffer.UV4Kind
  60832. * - BABYLON.VertexBuffer.UV5Kind
  60833. * - BABYLON.VertexBuffer.UV6Kind
  60834. * - BABYLON.VertexBuffer.ColorKind
  60835. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60836. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60837. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60838. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60839. *
  60840. * Returns the Mesh.
  60841. */
  60842. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60843. if (this.sourceMesh) {
  60844. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60845. }
  60846. return this.sourceMesh;
  60847. };
  60848. /**
  60849. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60850. * If the mesh has no geometry, it is simply returned as it is.
  60851. * The `data` are either a numeric array either a Float32Array.
  60852. * No new underlying VertexBuffer object is created.
  60853. * 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.
  60854. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60855. *
  60856. * Possible `kind` values :
  60857. * - BABYLON.VertexBuffer.PositionKind
  60858. * - BABYLON.VertexBuffer.UVKind
  60859. * - BABYLON.VertexBuffer.UV2Kind
  60860. * - BABYLON.VertexBuffer.UV3Kind
  60861. * - BABYLON.VertexBuffer.UV4Kind
  60862. * - BABYLON.VertexBuffer.UV5Kind
  60863. * - BABYLON.VertexBuffer.UV6Kind
  60864. * - BABYLON.VertexBuffer.ColorKind
  60865. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60866. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60867. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60868. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60869. *
  60870. * Returns the Mesh.
  60871. */
  60872. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60873. if (this.sourceMesh) {
  60874. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60875. }
  60876. return this.sourceMesh;
  60877. };
  60878. /**
  60879. * Sets the mesh indices.
  60880. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60881. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60882. * This method creates a new index buffer each call.
  60883. * Returns the Mesh.
  60884. */
  60885. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60886. if (totalVertices === void 0) { totalVertices = null; }
  60887. if (this.sourceMesh) {
  60888. this.sourceMesh.setIndices(indices, totalVertices);
  60889. }
  60890. return this.sourceMesh;
  60891. };
  60892. /**
  60893. * Boolean : True if the mesh owns the requested kind of data.
  60894. */
  60895. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60896. return this._sourceMesh.isVerticesDataPresent(kind);
  60897. };
  60898. /**
  60899. * Returns an array of indices (IndicesArray).
  60900. */
  60901. InstancedMesh.prototype.getIndices = function () {
  60902. return this._sourceMesh.getIndices();
  60903. };
  60904. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60905. get: function () {
  60906. return this._sourceMesh._positions;
  60907. },
  60908. enumerable: true,
  60909. configurable: true
  60910. });
  60911. /**
  60912. * Sets a new updated BoundingInfo to the mesh.
  60913. * Returns the mesh.
  60914. */
  60915. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60916. var meshBB = this._sourceMesh.getBoundingInfo();
  60917. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60918. this._updateBoundingInfo();
  60919. return this;
  60920. };
  60921. InstancedMesh.prototype._preActivate = function () {
  60922. if (this._currentLOD) {
  60923. this._currentLOD._preActivate();
  60924. }
  60925. return this;
  60926. };
  60927. InstancedMesh.prototype._activate = function (renderId) {
  60928. if (this._currentLOD) {
  60929. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60930. }
  60931. return this;
  60932. };
  60933. /**
  60934. * Returns the current associated LOD AbstractMesh.
  60935. */
  60936. InstancedMesh.prototype.getLOD = function (camera) {
  60937. if (!camera) {
  60938. return this;
  60939. }
  60940. var boundingInfo = this.getBoundingInfo();
  60941. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60942. if (this._currentLOD === this.sourceMesh) {
  60943. return this;
  60944. }
  60945. return this._currentLOD;
  60946. };
  60947. InstancedMesh.prototype._syncSubMeshes = function () {
  60948. this.releaseSubMeshes();
  60949. if (this._sourceMesh.subMeshes) {
  60950. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60951. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60952. }
  60953. }
  60954. return this;
  60955. };
  60956. InstancedMesh.prototype._generatePointsArray = function () {
  60957. return this._sourceMesh._generatePointsArray();
  60958. };
  60959. /**
  60960. * Creates a new InstancedMesh from the current mesh.
  60961. * - name (string) : the cloned mesh name
  60962. * - newParent (optional Node) : the optional Node to parent the clone to.
  60963. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60964. *
  60965. * Returns the clone.
  60966. */
  60967. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60968. var result = this._sourceMesh.createInstance(name);
  60969. // Deep copy
  60970. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60971. // Bounding info
  60972. this.refreshBoundingInfo();
  60973. // Parent
  60974. if (newParent) {
  60975. result.parent = newParent;
  60976. }
  60977. if (!doNotCloneChildren) {
  60978. // Children
  60979. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60980. var mesh = this.getScene().meshes[index];
  60981. if (mesh.parent === this) {
  60982. mesh.clone(mesh.name, result);
  60983. }
  60984. }
  60985. }
  60986. result.computeWorldMatrix(true);
  60987. return result;
  60988. };
  60989. /**
  60990. * Disposes the InstancedMesh.
  60991. * Returns nothing.
  60992. */
  60993. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60994. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60995. // Remove from mesh
  60996. var index = this._sourceMesh.instances.indexOf(this);
  60997. this._sourceMesh.instances.splice(index, 1);
  60998. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60999. };
  61000. return InstancedMesh;
  61001. }(BABYLON.AbstractMesh));
  61002. BABYLON.InstancedMesh = InstancedMesh;
  61003. })(BABYLON || (BABYLON = {}));
  61004. //# sourceMappingURL=babylon.instancedMesh.js.map
  61005. var BABYLON;
  61006. (function (BABYLON) {
  61007. var LinesMesh = /** @class */ (function (_super) {
  61008. __extends(LinesMesh, _super);
  61009. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61010. if (scene === void 0) { scene = null; }
  61011. if (parent === void 0) { parent = null; }
  61012. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61013. _this.useVertexColor = useVertexColor;
  61014. _this.useVertexAlpha = useVertexAlpha;
  61015. _this.color = new BABYLON.Color3(1, 1, 1);
  61016. _this.alpha = 1;
  61017. if (source) {
  61018. _this.color = source.color.clone();
  61019. _this.alpha = source.alpha;
  61020. _this.useVertexColor = source.useVertexColor;
  61021. _this.useVertexAlpha = source.useVertexAlpha;
  61022. }
  61023. _this._intersectionThreshold = 0.1;
  61024. var defines = [];
  61025. var options = {
  61026. attributes: [BABYLON.VertexBuffer.PositionKind],
  61027. uniforms: ["world", "viewProjection"],
  61028. needAlphaBlending: true,
  61029. defines: defines
  61030. };
  61031. if (useVertexAlpha === false) {
  61032. options.needAlphaBlending = false;
  61033. }
  61034. if (!useVertexColor) {
  61035. options.uniforms.push("color");
  61036. }
  61037. else {
  61038. options.defines.push("#define VERTEXCOLOR");
  61039. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61040. }
  61041. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61042. return _this;
  61043. }
  61044. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61045. /**
  61046. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61047. * This margin is expressed in world space coordinates, so its value may vary.
  61048. * Default value is 0.1
  61049. * @returns the intersection Threshold value.
  61050. */
  61051. get: function () {
  61052. return this._intersectionThreshold;
  61053. },
  61054. /**
  61055. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61056. * This margin is expressed in world space coordinates, so its value may vary.
  61057. * @param value the new threshold to apply
  61058. */
  61059. set: function (value) {
  61060. if (this._intersectionThreshold === value) {
  61061. return;
  61062. }
  61063. this._intersectionThreshold = value;
  61064. if (this.geometry) {
  61065. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61066. }
  61067. },
  61068. enumerable: true,
  61069. configurable: true
  61070. });
  61071. /**
  61072. * Returns the string "LineMesh"
  61073. */
  61074. LinesMesh.prototype.getClassName = function () {
  61075. return "LinesMesh";
  61076. };
  61077. Object.defineProperty(LinesMesh.prototype, "material", {
  61078. get: function () {
  61079. return this._colorShader;
  61080. },
  61081. set: function (value) {
  61082. // Do nothing
  61083. },
  61084. enumerable: true,
  61085. configurable: true
  61086. });
  61087. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61088. get: function () {
  61089. return false;
  61090. },
  61091. enumerable: true,
  61092. configurable: true
  61093. });
  61094. LinesMesh.prototype.createInstance = function (name) {
  61095. throw new Error("LinesMeshes do not support createInstance.");
  61096. };
  61097. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61098. if (!this._geometry) {
  61099. return this;
  61100. }
  61101. // VBOs
  61102. this._geometry._bind(this._colorShader.getEffect());
  61103. // Color
  61104. if (!this.useVertexColor) {
  61105. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61106. }
  61107. return this;
  61108. };
  61109. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61110. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61111. return this;
  61112. }
  61113. var engine = this.getScene().getEngine();
  61114. // Draw order
  61115. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61116. return this;
  61117. };
  61118. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61119. this._colorShader.dispose();
  61120. _super.prototype.dispose.call(this, doNotRecurse);
  61121. };
  61122. /**
  61123. * Returns a new LineMesh object cloned from the current one.
  61124. */
  61125. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61126. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61127. };
  61128. return LinesMesh;
  61129. }(BABYLON.Mesh));
  61130. BABYLON.LinesMesh = LinesMesh;
  61131. })(BABYLON || (BABYLON = {}));
  61132. //# sourceMappingURL=babylon.linesMesh.js.map
  61133. var BABYLON;
  61134. (function (BABYLON) {
  61135. /**
  61136. * Class containing static functions to help procedurally build meshes
  61137. */
  61138. var MeshBuilder = /** @class */ (function () {
  61139. function MeshBuilder() {
  61140. }
  61141. MeshBuilder.updateSideOrientation = function (orientation) {
  61142. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  61143. return BABYLON.Mesh.DOUBLESIDE;
  61144. }
  61145. if (orientation === undefined || orientation === null) {
  61146. return BABYLON.Mesh.FRONTSIDE;
  61147. }
  61148. return orientation;
  61149. };
  61150. /**
  61151. * Creates a box mesh
  61152. * * The parameter `size` sets the size (float) of each box side (default 1)
  61153. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  61154. * * 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)
  61155. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61156. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61157. * * 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
  61158. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61159. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  61160. * @param name defines the name of the mesh
  61161. * @param options defines the options used to create the mesh
  61162. * @param scene defines the hosting scene
  61163. * @returns the box mesh
  61164. */
  61165. MeshBuilder.CreateBox = function (name, options, scene) {
  61166. if (scene === void 0) { scene = null; }
  61167. var box = new BABYLON.Mesh(name, scene);
  61168. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61169. box._originalBuilderSideOrientation = options.sideOrientation;
  61170. var vertexData = BABYLON.VertexData.CreateBox(options);
  61171. vertexData.applyToMesh(box, options.updatable);
  61172. return box;
  61173. };
  61174. /**
  61175. * Creates a sphere mesh
  61176. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61177. * * 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`)
  61178. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61179. * * 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
  61180. * * 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)
  61181. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61182. * * 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
  61183. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61184. * @param name defines the name of the mesh
  61185. * @param options defines the options used to create the mesh
  61186. * @param scene defines the hosting scene
  61187. * @returns the sphere mesh
  61188. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61189. */
  61190. MeshBuilder.CreateSphere = function (name, options, scene) {
  61191. var sphere = new BABYLON.Mesh(name, scene);
  61192. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61193. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61194. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61195. vertexData.applyToMesh(sphere, options.updatable);
  61196. return sphere;
  61197. };
  61198. /**
  61199. * Creates a plane polygonal mesh. By default, this is a disc
  61200. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61201. * * 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
  61202. * * 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
  61203. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61204. * * 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
  61205. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61206. * @param name defines the name of the mesh
  61207. * @param options defines the options used to create the mesh
  61208. * @param scene defines the hosting scene
  61209. * @returns the plane polygonal mesh
  61210. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61211. */
  61212. MeshBuilder.CreateDisc = function (name, options, scene) {
  61213. if (scene === void 0) { scene = null; }
  61214. var disc = new BABYLON.Mesh(name, scene);
  61215. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61216. disc._originalBuilderSideOrientation = options.sideOrientation;
  61217. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61218. vertexData.applyToMesh(disc, options.updatable);
  61219. return disc;
  61220. };
  61221. /**
  61222. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61223. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61224. * * 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`)
  61225. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61226. * * 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
  61227. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61228. * * 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
  61229. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61230. * @param name defines the name of the mesh
  61231. * @param options defines the options used to create the mesh
  61232. * @param scene defines the hosting scene
  61233. * @returns the icosahedron mesh
  61234. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61235. */
  61236. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61237. var sphere = new BABYLON.Mesh(name, scene);
  61238. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61239. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61240. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61241. vertexData.applyToMesh(sphere, options.updatable);
  61242. return sphere;
  61243. };
  61244. ;
  61245. /**
  61246. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61247. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61248. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61249. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61250. * * 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
  61251. * * 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
  61252. * * 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
  61253. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61254. * * 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
  61255. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61256. * * 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
  61257. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61258. * * 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
  61259. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61260. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61261. * @param name defines the name of the mesh
  61262. * @param options defines the options used to create the mesh
  61263. * @param scene defines the hosting scene
  61264. * @returns the ribbon mesh
  61265. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61266. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61267. */
  61268. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61269. if (scene === void 0) { scene = null; }
  61270. var pathArray = options.pathArray;
  61271. var closeArray = options.closeArray;
  61272. var closePath = options.closePath;
  61273. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61274. var instance = options.instance;
  61275. var updatable = options.updatable;
  61276. if (instance) { // existing ribbon instance update
  61277. // positionFunction : ribbon case
  61278. // only pathArray and sideOrientation parameters are taken into account for positions update
  61279. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61280. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61281. var positionFunction = function (positions) {
  61282. var minlg = pathArray[0].length;
  61283. var i = 0;
  61284. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61285. for (var si = 1; si <= ns; si++) {
  61286. for (var p = 0; p < pathArray.length; p++) {
  61287. var path = pathArray[p];
  61288. var l = path.length;
  61289. minlg = (minlg < l) ? minlg : l;
  61290. var j = 0;
  61291. while (j < minlg) {
  61292. positions[i] = path[j].x;
  61293. positions[i + 1] = path[j].y;
  61294. positions[i + 2] = path[j].z;
  61295. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61296. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61297. }
  61298. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61299. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61300. }
  61301. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61302. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61303. }
  61304. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61305. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61306. }
  61307. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61308. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61309. }
  61310. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61311. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61312. }
  61313. j++;
  61314. i += 3;
  61315. }
  61316. if (instance._closePath) {
  61317. positions[i] = path[0].x;
  61318. positions[i + 1] = path[0].y;
  61319. positions[i + 2] = path[0].z;
  61320. i += 3;
  61321. }
  61322. }
  61323. }
  61324. };
  61325. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61326. positionFunction(positions);
  61327. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61328. instance._boundingInfo.update(instance._worldMatrix);
  61329. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61330. if (options.colors) {
  61331. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61332. for (var c = 0; c < options.colors.length; c++) {
  61333. colors[c * 4] = options.colors[c].r;
  61334. colors[c * 4 + 1] = options.colors[c].g;
  61335. colors[c * 4 + 2] = options.colors[c].b;
  61336. colors[c * 4 + 3] = options.colors[c].a;
  61337. }
  61338. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61339. }
  61340. if (options.uvs) {
  61341. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61342. for (var i = 0; i < options.uvs.length; i++) {
  61343. uvs[i * 2] = options.uvs[i].x;
  61344. uvs[i * 2 + 1] = options.uvs[i].y;
  61345. }
  61346. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61347. }
  61348. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61349. var indices = instance.getIndices();
  61350. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61351. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61352. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61353. if (instance._closePath) {
  61354. var indexFirst = 0;
  61355. var indexLast = 0;
  61356. for (var p = 0; p < pathArray.length; p++) {
  61357. indexFirst = instance._idx[p] * 3;
  61358. if (p + 1 < pathArray.length) {
  61359. indexLast = (instance._idx[p + 1] - 1) * 3;
  61360. }
  61361. else {
  61362. indexLast = normals.length - 3;
  61363. }
  61364. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61365. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61366. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61367. normals[indexLast] = normals[indexFirst];
  61368. normals[indexLast + 1] = normals[indexFirst + 1];
  61369. normals[indexLast + 2] = normals[indexFirst + 2];
  61370. }
  61371. }
  61372. if (!(instance.areNormalsFrozen)) {
  61373. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61374. }
  61375. }
  61376. return instance;
  61377. }
  61378. else { // new ribbon creation
  61379. var ribbon = new BABYLON.Mesh(name, scene);
  61380. ribbon._originalBuilderSideOrientation = sideOrientation;
  61381. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61382. if (closePath) {
  61383. ribbon._idx = vertexData._idx;
  61384. }
  61385. ribbon._closePath = closePath;
  61386. ribbon._closeArray = closeArray;
  61387. vertexData.applyToMesh(ribbon, updatable);
  61388. return ribbon;
  61389. }
  61390. };
  61391. /**
  61392. * Creates a cylinder or a cone mesh
  61393. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61394. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61395. * * 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.
  61396. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61397. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61398. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61399. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61400. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61401. * * 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).
  61402. * * 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
  61403. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61404. * * 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
  61405. * * 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.
  61406. * * If `enclose` is false, a ring surface is one element.
  61407. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61408. * * 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
  61409. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61410. * * 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
  61411. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61412. * @param name defines the name of the mesh
  61413. * @param options defines the options used to create the mesh
  61414. * @param scene defines the hosting scene
  61415. * @returns the cylinder mesh
  61416. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61417. */
  61418. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61419. var cylinder = new BABYLON.Mesh(name, scene);
  61420. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61421. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61422. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61423. vertexData.applyToMesh(cylinder, options.updatable);
  61424. return cylinder;
  61425. };
  61426. /**
  61427. * Creates a torus mesh
  61428. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61429. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61430. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61431. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61432. * * 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
  61433. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61434. * @param name defines the name of the mesh
  61435. * @param options defines the options used to create the mesh
  61436. * @param scene defines the hosting scene
  61437. * @returns the torus mesh
  61438. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61439. */
  61440. MeshBuilder.CreateTorus = function (name, options, scene) {
  61441. var torus = new BABYLON.Mesh(name, scene);
  61442. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61443. torus._originalBuilderSideOrientation = options.sideOrientation;
  61444. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61445. vertexData.applyToMesh(torus, options.updatable);
  61446. return torus;
  61447. };
  61448. /**
  61449. * Creates a torus knot mesh
  61450. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61451. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61452. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61453. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61454. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61455. * * 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
  61456. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61457. * @param name defines the name of the mesh
  61458. * @param options defines the options used to create the mesh
  61459. * @param scene defines the hosting scene
  61460. * @returns the torus knot mesh
  61461. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61462. */
  61463. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61464. var torusKnot = new BABYLON.Mesh(name, scene);
  61465. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61466. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61467. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61468. vertexData.applyToMesh(torusKnot, options.updatable);
  61469. return torusKnot;
  61470. };
  61471. /**
  61472. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61473. * * 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
  61474. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61475. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61476. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61477. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61478. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61479. * * 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
  61480. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61481. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61482. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61483. * @param name defines the name of the new line system
  61484. * @param options defines the options used to create the line system
  61485. * @param scene defines the hosting scene
  61486. * @returns a new line system mesh
  61487. */
  61488. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61489. var instance = options.instance;
  61490. var lines = options.lines;
  61491. var colors = options.colors;
  61492. if (instance) { // lines update
  61493. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61494. var vertexColor;
  61495. var lineColors;
  61496. if (colors) {
  61497. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61498. }
  61499. var i = 0;
  61500. var c = 0;
  61501. for (var l = 0; l < lines.length; l++) {
  61502. var points = lines[l];
  61503. for (var p = 0; p < points.length; p++) {
  61504. positions[i] = points[p].x;
  61505. positions[i + 1] = points[p].y;
  61506. positions[i + 2] = points[p].z;
  61507. if (colors && vertexColor) {
  61508. lineColors = colors[l];
  61509. vertexColor[c] = lineColors[p].r;
  61510. vertexColor[c + 1] = lineColors[p].g;
  61511. vertexColor[c + 2] = lineColors[p].b;
  61512. vertexColor[c + 3] = lineColors[p].a;
  61513. c += 4;
  61514. }
  61515. i += 3;
  61516. }
  61517. }
  61518. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61519. if (colors && vertexColor) {
  61520. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61521. }
  61522. return instance;
  61523. }
  61524. // line system creation
  61525. var useVertexColor = (colors) ? true : false;
  61526. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61527. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61528. vertexData.applyToMesh(lineSystem, options.updatable);
  61529. return lineSystem;
  61530. };
  61531. /**
  61532. * Creates a line mesh
  61533. * 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
  61534. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61535. * * The parameter `points` is an array successive Vector3
  61536. * * 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
  61537. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61538. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61539. * * When updating an instance, remember that only point positions can change, not the number of points
  61540. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61541. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61542. * @param name defines the name of the new line system
  61543. * @param options defines the options used to create the line system
  61544. * @param scene defines the hosting scene
  61545. * @returns a new line mesh
  61546. */
  61547. MeshBuilder.CreateLines = function (name, options, scene) {
  61548. if (scene === void 0) { scene = null; }
  61549. var colors = (options.colors) ? [options.colors] : null;
  61550. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61551. return lines;
  61552. };
  61553. /**
  61554. * Creates a dashed line mesh
  61555. * * 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
  61556. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61557. * * The parameter `points` is an array successive Vector3
  61558. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61559. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61560. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61561. * * 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
  61562. * * When updating an instance, remember that only point positions can change, not the number of points
  61563. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61564. * @param name defines the name of the mesh
  61565. * @param options defines the options used to create the mesh
  61566. * @param scene defines the hosting scene
  61567. * @returns the dashed line mesh
  61568. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61569. */
  61570. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61571. if (scene === void 0) { scene = null; }
  61572. var points = options.points;
  61573. var instance = options.instance;
  61574. var gapSize = options.gapSize || 1;
  61575. var dashSize = options.dashSize || 3;
  61576. if (instance) { // dashed lines update
  61577. var positionFunction = function (positions) {
  61578. var curvect = BABYLON.Vector3.Zero();
  61579. var nbSeg = positions.length / 6;
  61580. var lg = 0;
  61581. var nb = 0;
  61582. var shft = 0;
  61583. var dashshft = 0;
  61584. var curshft = 0;
  61585. var p = 0;
  61586. var i = 0;
  61587. var j = 0;
  61588. for (i = 0; i < points.length - 1; i++) {
  61589. points[i + 1].subtractToRef(points[i], curvect);
  61590. lg += curvect.length();
  61591. }
  61592. shft = lg / nbSeg;
  61593. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61594. for (i = 0; i < points.length - 1; i++) {
  61595. points[i + 1].subtractToRef(points[i], curvect);
  61596. nb = Math.floor(curvect.length() / shft);
  61597. curvect.normalize();
  61598. j = 0;
  61599. while (j < nb && p < positions.length) {
  61600. curshft = shft * j;
  61601. positions[p] = points[i].x + curshft * curvect.x;
  61602. positions[p + 1] = points[i].y + curshft * curvect.y;
  61603. positions[p + 2] = points[i].z + curshft * curvect.z;
  61604. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61605. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61606. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61607. p += 6;
  61608. j++;
  61609. }
  61610. }
  61611. while (p < positions.length) {
  61612. positions[p] = points[i].x;
  61613. positions[p + 1] = points[i].y;
  61614. positions[p + 2] = points[i].z;
  61615. p += 3;
  61616. }
  61617. };
  61618. instance.updateMeshPositions(positionFunction, false);
  61619. return instance;
  61620. }
  61621. // dashed lines creation
  61622. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61623. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61624. vertexData.applyToMesh(dashedLines, options.updatable);
  61625. dashedLines.dashSize = dashSize;
  61626. dashedLines.gapSize = gapSize;
  61627. return dashedLines;
  61628. };
  61629. /**
  61630. * 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.
  61631. * * 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.
  61632. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61633. * * 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.
  61634. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61635. * * 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
  61636. * * 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
  61637. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61638. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61639. * * 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
  61640. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61641. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61642. * @param name defines the name of the mesh
  61643. * @param options defines the options used to create the mesh
  61644. * @param scene defines the hosting scene
  61645. * @returns the extruded shape mesh
  61646. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61647. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61648. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61649. */
  61650. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61651. if (scene === void 0) { scene = null; }
  61652. var path = options.path;
  61653. var shape = options.shape;
  61654. var scale = options.scale || 1;
  61655. var rotation = options.rotation || 0;
  61656. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61657. var updatable = options.updatable;
  61658. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61659. var instance = options.instance || null;
  61660. var invertUV = options.invertUV || false;
  61661. 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);
  61662. };
  61663. /**
  61664. * Creates an custom extruded shape mesh.
  61665. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61666. * * 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.
  61667. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61668. * * 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
  61669. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61670. * * 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
  61671. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61672. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61673. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61674. * * 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
  61675. * * 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
  61676. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61677. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61678. * * 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
  61679. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61680. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61681. * @param name defines the name of the mesh
  61682. * @param options defines the options used to create the mesh
  61683. * @param scene defines the hosting scene
  61684. * @returns the custom extruded shape mesh
  61685. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61686. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61687. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61688. */
  61689. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61690. var path = options.path;
  61691. var shape = options.shape;
  61692. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61693. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61694. var ribbonCloseArray = options.ribbonCloseArray || false;
  61695. var ribbonClosePath = options.ribbonClosePath || false;
  61696. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61697. var updatable = options.updatable;
  61698. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61699. var instance = options.instance;
  61700. var invertUV = options.invertUV || false;
  61701. 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);
  61702. };
  61703. /**
  61704. * Creates lathe mesh.
  61705. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61706. * * 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
  61707. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61708. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61709. * * 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
  61710. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61711. * * 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
  61712. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61713. * * 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
  61714. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61715. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61716. * @param name defines the name of the mesh
  61717. * @param options defines the options used to create the mesh
  61718. * @param scene defines the hosting scene
  61719. * @returns the lathe mesh
  61720. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61721. */
  61722. MeshBuilder.CreateLathe = function (name, options, scene) {
  61723. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61724. var closed = (options.closed === undefined) ? true : options.closed;
  61725. var shape = options.shape;
  61726. var radius = options.radius || 1;
  61727. var tessellation = options.tessellation || 64;
  61728. var updatable = options.updatable;
  61729. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61730. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61731. var pi2 = Math.PI * 2;
  61732. var paths = new Array();
  61733. var invertUV = options.invertUV || false;
  61734. var i = 0;
  61735. var p = 0;
  61736. var step = pi2 / tessellation * arc;
  61737. var rotated;
  61738. var path = new Array();
  61739. for (i = 0; i <= tessellation; i++) {
  61740. var path = [];
  61741. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61742. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61743. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61744. }
  61745. for (p = 0; p < shape.length; p++) {
  61746. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61747. path.push(rotated);
  61748. }
  61749. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61750. 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));
  61751. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61752. }
  61753. paths.push(path);
  61754. }
  61755. // lathe ribbon
  61756. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61757. return lathe;
  61758. };
  61759. /**
  61760. * Creates a plane mesh
  61761. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61762. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61763. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61764. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61765. * * 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
  61766. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61767. * @param name defines the name of the mesh
  61768. * @param options defines the options used to create the mesh
  61769. * @param scene defines the hosting scene
  61770. * @returns the plane mesh
  61771. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61772. */
  61773. MeshBuilder.CreatePlane = function (name, options, scene) {
  61774. var plane = new BABYLON.Mesh(name, scene);
  61775. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61776. plane._originalBuilderSideOrientation = options.sideOrientation;
  61777. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61778. vertexData.applyToMesh(plane, options.updatable);
  61779. if (options.sourcePlane) {
  61780. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61781. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61782. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61783. plane.rotate(vectorProduct, product);
  61784. }
  61785. return plane;
  61786. };
  61787. /**
  61788. * Creates a ground mesh
  61789. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61790. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61791. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61792. * @param name defines the name of the mesh
  61793. * @param options defines the options used to create the mesh
  61794. * @param scene defines the hosting scene
  61795. * @returns the ground mesh
  61796. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61797. */
  61798. MeshBuilder.CreateGround = function (name, options, scene) {
  61799. var ground = new BABYLON.GroundMesh(name, scene);
  61800. ground._setReady(false);
  61801. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61802. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61803. ground._width = options.width || 1;
  61804. ground._height = options.height || 1;
  61805. ground._maxX = ground._width / 2;
  61806. ground._maxZ = ground._height / 2;
  61807. ground._minX = -ground._maxX;
  61808. ground._minZ = -ground._maxZ;
  61809. var vertexData = BABYLON.VertexData.CreateGround(options);
  61810. vertexData.applyToMesh(ground, options.updatable);
  61811. ground._setReady(true);
  61812. return ground;
  61813. };
  61814. /**
  61815. * Creates a tiled ground mesh
  61816. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61817. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61818. * * 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
  61819. * * 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
  61820. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61821. * @param name defines the name of the mesh
  61822. * @param options defines the options used to create the mesh
  61823. * @param scene defines the hosting scene
  61824. * @returns the tiled ground mesh
  61825. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61826. */
  61827. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61828. var tiledGround = new BABYLON.Mesh(name, scene);
  61829. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61830. vertexData.applyToMesh(tiledGround, options.updatable);
  61831. return tiledGround;
  61832. };
  61833. /**
  61834. * Creates a ground mesh from a height map
  61835. * * The parameter `url` sets the URL of the height map image resource.
  61836. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61837. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61838. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61839. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61840. * * 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.
  61841. * * 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).
  61842. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61843. * @param name defines the name of the mesh
  61844. * @param url defines the url to the height map
  61845. * @param options defines the options used to create the mesh
  61846. * @param scene defines the hosting scene
  61847. * @returns the ground mesh
  61848. * @see http://doc.babylonjs.com/babylon101/height_map
  61849. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61850. */
  61851. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61852. var width = options.width || 10.0;
  61853. var height = options.height || 10.0;
  61854. var subdivisions = options.subdivisions || 1 | 0;
  61855. var minHeight = options.minHeight || 0.0;
  61856. var maxHeight = options.maxHeight || 1.0;
  61857. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61858. var updatable = options.updatable;
  61859. var onReady = options.onReady;
  61860. var ground = new BABYLON.GroundMesh(name, scene);
  61861. ground._subdivisionsX = subdivisions;
  61862. ground._subdivisionsY = subdivisions;
  61863. ground._width = width;
  61864. ground._height = height;
  61865. ground._maxX = ground._width / 2.0;
  61866. ground._maxZ = ground._height / 2.0;
  61867. ground._minX = -ground._maxX;
  61868. ground._minZ = -ground._maxZ;
  61869. ground._setReady(false);
  61870. var onload = function (img) {
  61871. // Getting height map data
  61872. var canvas = document.createElement("canvas");
  61873. var context = canvas.getContext("2d");
  61874. if (!context) {
  61875. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61876. }
  61877. if (scene.isDisposed) {
  61878. return;
  61879. }
  61880. var bufferWidth = img.width;
  61881. var bufferHeight = img.height;
  61882. canvas.width = bufferWidth;
  61883. canvas.height = bufferHeight;
  61884. context.drawImage(img, 0, 0);
  61885. // Create VertexData from map data
  61886. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61887. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61888. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61889. width: width, height: height,
  61890. subdivisions: subdivisions,
  61891. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61892. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61893. });
  61894. vertexData.applyToMesh(ground, updatable);
  61895. //execute ready callback, if set
  61896. if (onReady) {
  61897. onReady(ground);
  61898. }
  61899. ground._setReady(true);
  61900. };
  61901. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61902. return ground;
  61903. };
  61904. /**
  61905. * Creates a polygon mesh
  61906. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61907. * * 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
  61908. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61909. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61910. * * 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)
  61911. * * Remember you can only change the shape positions, not their number when updating a polygon
  61912. * @param name defines the name of the mesh
  61913. * @param options defines the options used to create the mesh
  61914. * @param scene defines the hosting scene
  61915. * @returns the polygon mesh
  61916. */
  61917. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61918. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61919. var shape = options.shape;
  61920. var holes = options.holes || [];
  61921. var depth = options.depth || 0;
  61922. var contours = [];
  61923. var hole = [];
  61924. for (var i = 0; i < shape.length; i++) {
  61925. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61926. }
  61927. var epsilon = 0.00000001;
  61928. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61929. contours.pop();
  61930. }
  61931. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61932. for (var hNb = 0; hNb < holes.length; hNb++) {
  61933. hole = [];
  61934. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61935. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61936. }
  61937. polygonTriangulation.addHole(hole);
  61938. }
  61939. var polygon = polygonTriangulation.build(options.updatable, depth);
  61940. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61941. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61942. vertexData.applyToMesh(polygon, options.updatable);
  61943. return polygon;
  61944. };
  61945. ;
  61946. /**
  61947. * Creates an extruded polygon mesh, with depth in the Y direction.
  61948. * * 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)
  61949. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61950. * @param name defines the name of the mesh
  61951. * @param options defines the options used to create the mesh
  61952. * @param scene defines the hosting scene
  61953. * @returns the polygon mesh
  61954. */
  61955. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61956. return MeshBuilder.CreatePolygon(name, options, scene);
  61957. };
  61958. ;
  61959. /**
  61960. * Creates a tube mesh.
  61961. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61962. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61963. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61964. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61965. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61966. * * 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)
  61967. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61968. * * 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
  61969. * * 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
  61970. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61971. * * 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
  61972. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61973. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61974. * @param name defines the name of the mesh
  61975. * @param options defines the options used to create the mesh
  61976. * @param scene defines the hosting scene
  61977. * @returns the tube mesh
  61978. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61979. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61980. */
  61981. MeshBuilder.CreateTube = function (name, options, scene) {
  61982. var path = options.path;
  61983. var instance = options.instance;
  61984. var radius = 1.0;
  61985. if (instance) {
  61986. radius = instance.radius;
  61987. }
  61988. if (options.radius !== undefined) {
  61989. radius = options.radius;
  61990. }
  61991. ;
  61992. var tessellation = options.tessellation || 64 | 0;
  61993. var radiusFunction = options.radiusFunction || null;
  61994. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61995. var invertUV = options.invertUV || false;
  61996. var updatable = options.updatable;
  61997. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61998. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61999. // tube geometry
  62000. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  62001. var tangents = path3D.getTangents();
  62002. var normals = path3D.getNormals();
  62003. var distances = path3D.getDistances();
  62004. var pi2 = Math.PI * 2;
  62005. var step = pi2 / tessellation * arc;
  62006. var returnRadius = function () { return radius; };
  62007. var radiusFunctionFinal = radiusFunction || returnRadius;
  62008. var circlePath;
  62009. var rad;
  62010. var normal;
  62011. var rotated;
  62012. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62013. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62014. for (var i = 0; i < path.length; i++) {
  62015. rad = radiusFunctionFinal(i, distances[i]); // current radius
  62016. circlePath = Array(); // current circle array
  62017. normal = normals[i]; // current normal
  62018. for (var t = 0; t < tessellation; t++) {
  62019. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  62020. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  62021. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  62022. rotated.scaleInPlace(rad).addInPlace(path[i]);
  62023. circlePath[t] = rotated;
  62024. }
  62025. circlePaths[index] = circlePath;
  62026. index++;
  62027. }
  62028. // cap
  62029. var capPath = function (nbPoints, pathIndex) {
  62030. var pointCap = Array();
  62031. for (var i = 0; i < nbPoints; i++) {
  62032. pointCap.push(path[pathIndex]);
  62033. }
  62034. return pointCap;
  62035. };
  62036. switch (cap) {
  62037. case BABYLON.Mesh.NO_CAP:
  62038. break;
  62039. case BABYLON.Mesh.CAP_START:
  62040. circlePaths[0] = capPath(tessellation, 0);
  62041. circlePaths[1] = circlePaths[2].slice(0);
  62042. break;
  62043. case BABYLON.Mesh.CAP_END:
  62044. circlePaths[index] = circlePaths[index - 1].slice(0);
  62045. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62046. break;
  62047. case BABYLON.Mesh.CAP_ALL:
  62048. circlePaths[0] = capPath(tessellation, 0);
  62049. circlePaths[1] = circlePaths[2].slice(0);
  62050. circlePaths[index] = circlePaths[index - 1].slice(0);
  62051. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62052. break;
  62053. default:
  62054. break;
  62055. }
  62056. return circlePaths;
  62057. };
  62058. var path3D;
  62059. var pathArray;
  62060. if (instance) { // tube update
  62061. var arc = options.arc || instance.arc;
  62062. path3D = (instance.path3D).update(path);
  62063. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  62064. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  62065. instance.path3D = path3D;
  62066. instance.pathArray = pathArray;
  62067. instance.arc = arc;
  62068. instance.radius = radius;
  62069. return instance;
  62070. }
  62071. // tube creation
  62072. path3D = new BABYLON.Path3D(path);
  62073. var newPathArray = new Array();
  62074. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62075. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62076. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62077. tube.pathArray = pathArray;
  62078. tube.path3D = path3D;
  62079. tube.tessellation = tessellation;
  62080. tube.cap = cap;
  62081. tube.arc = options.arc;
  62082. tube.radius = radius;
  62083. return tube;
  62084. };
  62085. /**
  62086. * Creates a polyhedron mesh
  62087. * * 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
  62088. * * The parameter `size` (positive float, default 1) sets the polygon size
  62089. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62090. * * 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`
  62091. * * 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
  62092. * * 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)`)
  62093. * * 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
  62094. * * 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
  62095. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62096. * * 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
  62097. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62098. * @param name defines the name of the mesh
  62099. * @param options defines the options used to create the mesh
  62100. * @param scene defines the hosting scene
  62101. * @returns the polyhedron mesh
  62102. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62103. */
  62104. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62105. var polyhedron = new BABYLON.Mesh(name, scene);
  62106. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62107. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62108. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62109. vertexData.applyToMesh(polyhedron, options.updatable);
  62110. return polyhedron;
  62111. };
  62112. /**
  62113. * Creates a decal mesh.
  62114. * 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
  62115. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62116. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62117. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62118. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62119. * @param name defines the name of the mesh
  62120. * @param sourceMesh defines the mesh where the decal must be applied
  62121. * @param options defines the options used to create the mesh
  62122. * @param scene defines the hosting scene
  62123. * @returns the decal mesh
  62124. * @see http://doc.babylonjs.com/how_to/decals
  62125. */
  62126. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62127. var indices = sourceMesh.getIndices();
  62128. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62129. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62130. var position = options.position || BABYLON.Vector3.Zero();
  62131. var normal = options.normal || BABYLON.Vector3.Up();
  62132. var size = options.size || BABYLON.Vector3.One();
  62133. var angle = options.angle || 0;
  62134. // Getting correct rotation
  62135. if (!normal) {
  62136. var target = new BABYLON.Vector3(0, 0, 1);
  62137. var camera = sourceMesh.getScene().activeCamera;
  62138. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62139. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62140. }
  62141. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  62142. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  62143. var pitch = Math.atan2(normal.y, len);
  62144. // Matrix
  62145. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  62146. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  62147. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  62148. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  62149. var vertexData = new BABYLON.VertexData();
  62150. vertexData.indices = [];
  62151. vertexData.positions = [];
  62152. vertexData.normals = [];
  62153. vertexData.uvs = [];
  62154. var currentVertexDataIndex = 0;
  62155. var extractDecalVector3 = function (indexId) {
  62156. var result = new BABYLON.PositionNormalVertex();
  62157. if (!indices || !positions || !normals) {
  62158. return result;
  62159. }
  62160. var vertexId = indices[indexId];
  62161. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  62162. // Send vector to decal local world
  62163. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  62164. // Get normal
  62165. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62166. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62167. return result;
  62168. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62169. var clip = function (vertices, axis) {
  62170. if (vertices.length === 0) {
  62171. return vertices;
  62172. }
  62173. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62174. var clipVertices = function (v0, v1) {
  62175. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62176. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62177. };
  62178. var result = new Array();
  62179. for (var index = 0; index < vertices.length; index += 3) {
  62180. var v1Out;
  62181. var v2Out;
  62182. var v3Out;
  62183. var total = 0;
  62184. var nV1 = null;
  62185. var nV2 = null;
  62186. var nV3 = null;
  62187. var nV4 = null;
  62188. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62189. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62190. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62191. v1Out = d1 > 0;
  62192. v2Out = d2 > 0;
  62193. v3Out = d3 > 0;
  62194. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62195. switch (total) {
  62196. case 0:
  62197. result.push(vertices[index]);
  62198. result.push(vertices[index + 1]);
  62199. result.push(vertices[index + 2]);
  62200. break;
  62201. case 1:
  62202. if (v1Out) {
  62203. nV1 = vertices[index + 1];
  62204. nV2 = vertices[index + 2];
  62205. nV3 = clipVertices(vertices[index], nV1);
  62206. nV4 = clipVertices(vertices[index], nV2);
  62207. }
  62208. if (v2Out) {
  62209. nV1 = vertices[index];
  62210. nV2 = vertices[index + 2];
  62211. nV3 = clipVertices(vertices[index + 1], nV1);
  62212. nV4 = clipVertices(vertices[index + 1], nV2);
  62213. result.push(nV3);
  62214. result.push(nV2.clone());
  62215. result.push(nV1.clone());
  62216. result.push(nV2.clone());
  62217. result.push(nV3.clone());
  62218. result.push(nV4);
  62219. break;
  62220. }
  62221. if (v3Out) {
  62222. nV1 = vertices[index];
  62223. nV2 = vertices[index + 1];
  62224. nV3 = clipVertices(vertices[index + 2], nV1);
  62225. nV4 = clipVertices(vertices[index + 2], nV2);
  62226. }
  62227. if (nV1 && nV2 && nV3 && nV4) {
  62228. result.push(nV1.clone());
  62229. result.push(nV2.clone());
  62230. result.push(nV3);
  62231. result.push(nV4);
  62232. result.push(nV3.clone());
  62233. result.push(nV2.clone());
  62234. }
  62235. break;
  62236. case 2:
  62237. if (!v1Out) {
  62238. nV1 = vertices[index].clone();
  62239. nV2 = clipVertices(nV1, vertices[index + 1]);
  62240. nV3 = clipVertices(nV1, vertices[index + 2]);
  62241. result.push(nV1);
  62242. result.push(nV2);
  62243. result.push(nV3);
  62244. }
  62245. if (!v2Out) {
  62246. nV1 = vertices[index + 1].clone();
  62247. nV2 = clipVertices(nV1, vertices[index + 2]);
  62248. nV3 = clipVertices(nV1, vertices[index]);
  62249. result.push(nV1);
  62250. result.push(nV2);
  62251. result.push(nV3);
  62252. }
  62253. if (!v3Out) {
  62254. nV1 = vertices[index + 2].clone();
  62255. nV2 = clipVertices(nV1, vertices[index]);
  62256. nV3 = clipVertices(nV1, vertices[index + 1]);
  62257. result.push(nV1);
  62258. result.push(nV2);
  62259. result.push(nV3);
  62260. }
  62261. break;
  62262. case 3:
  62263. break;
  62264. }
  62265. }
  62266. return result;
  62267. };
  62268. for (var index = 0; index < indices.length; index += 3) {
  62269. var faceVertices = new Array();
  62270. faceVertices.push(extractDecalVector3(index));
  62271. faceVertices.push(extractDecalVector3(index + 1));
  62272. faceVertices.push(extractDecalVector3(index + 2));
  62273. // Clip
  62274. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62275. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62276. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62277. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62278. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62279. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62280. if (faceVertices.length === 0) {
  62281. continue;
  62282. }
  62283. // Add UVs and get back to world
  62284. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62285. var vertex = faceVertices[vIndex];
  62286. //TODO check for Int32Array | Uint32Array | Uint16Array
  62287. vertexData.indices.push(currentVertexDataIndex);
  62288. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62289. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62290. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62291. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62292. currentVertexDataIndex++;
  62293. }
  62294. }
  62295. // Return mesh
  62296. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62297. vertexData.applyToMesh(decal);
  62298. decal.position = position.clone();
  62299. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62300. return decal;
  62301. };
  62302. // Privates
  62303. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62304. // extrusion geometry
  62305. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62306. var tangents = path3D.getTangents();
  62307. var normals = path3D.getNormals();
  62308. var binormals = path3D.getBinormals();
  62309. var distances = path3D.getDistances();
  62310. var angle = 0;
  62311. var returnScale = function () { return scale !== null ? scale : 1; };
  62312. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62313. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62314. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62315. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62316. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62317. for (var i = 0; i < curve.length; i++) {
  62318. var shapePath = new Array();
  62319. var angleStep = rotate(i, distances[i]);
  62320. var scaleRatio = scl(i, distances[i]);
  62321. for (var p = 0; p < shape.length; p++) {
  62322. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62323. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62324. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62325. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62326. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62327. shapePath[p] = rotated;
  62328. }
  62329. shapePaths[index] = shapePath;
  62330. angle += angleStep;
  62331. index++;
  62332. }
  62333. // cap
  62334. var capPath = function (shapePath) {
  62335. var pointCap = Array();
  62336. var barycenter = BABYLON.Vector3.Zero();
  62337. var i;
  62338. for (i = 0; i < shapePath.length; i++) {
  62339. barycenter.addInPlace(shapePath[i]);
  62340. }
  62341. barycenter.scaleInPlace(1.0 / shapePath.length);
  62342. for (i = 0; i < shapePath.length; i++) {
  62343. pointCap.push(barycenter);
  62344. }
  62345. return pointCap;
  62346. };
  62347. switch (cap) {
  62348. case BABYLON.Mesh.NO_CAP:
  62349. break;
  62350. case BABYLON.Mesh.CAP_START:
  62351. shapePaths[0] = capPath(shapePaths[2]);
  62352. shapePaths[1] = shapePaths[2];
  62353. break;
  62354. case BABYLON.Mesh.CAP_END:
  62355. shapePaths[index] = shapePaths[index - 1];
  62356. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62357. break;
  62358. case BABYLON.Mesh.CAP_ALL:
  62359. shapePaths[0] = capPath(shapePaths[2]);
  62360. shapePaths[1] = shapePaths[2];
  62361. shapePaths[index] = shapePaths[index - 1];
  62362. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62363. break;
  62364. default:
  62365. break;
  62366. }
  62367. return shapePaths;
  62368. };
  62369. var path3D;
  62370. var pathArray;
  62371. if (instance) { // instance update
  62372. path3D = (instance.path3D).update(curve);
  62373. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62374. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62375. return instance;
  62376. }
  62377. // extruded shape creation
  62378. path3D = new BABYLON.Path3D(curve);
  62379. var newShapePaths = new Array();
  62380. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62381. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62382. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62383. extrudedGeneric.pathArray = pathArray;
  62384. extrudedGeneric.path3D = path3D;
  62385. extrudedGeneric.cap = cap;
  62386. return extrudedGeneric;
  62387. };
  62388. return MeshBuilder;
  62389. }());
  62390. BABYLON.MeshBuilder = MeshBuilder;
  62391. })(BABYLON || (BABYLON = {}));
  62392. //# sourceMappingURL=babylon.meshBuilder.js.map
  62393. var BABYLON;
  62394. (function (BABYLON) {
  62395. /**
  62396. * Draco compression (https://google.github.io/draco/)
  62397. *
  62398. * This class wraps the Draco module.
  62399. *
  62400. * **Encoder**
  62401. *
  62402. * The encoder is not currently implemented.
  62403. *
  62404. * **Decoder**
  62405. *
  62406. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62407. *
  62408. * To update the configuration, use the following code:
  62409. * ```javascript
  62410. * BABYLON.DracoCompression.Configuration = {
  62411. * decoder: {
  62412. * wasmUrl: "<url to the WebAssembly library>",
  62413. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62414. * fallbackUrl: "<url to the fallback JavaScript library>",
  62415. * }
  62416. * };
  62417. * ```
  62418. *
  62419. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62420. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62421. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62422. *
  62423. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62424. * ```javascript
  62425. * var dracoCompression = new BABYLON.DracoCompression();
  62426. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62427. * [BABYLON.VertexBuffer.PositionKind]: 0
  62428. * });
  62429. * ```
  62430. *
  62431. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62432. */
  62433. var DracoCompression = /** @class */ (function () {
  62434. /**
  62435. * Constructor
  62436. */
  62437. function DracoCompression() {
  62438. }
  62439. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62440. /**
  62441. * Returns true if the decoder is available.
  62442. */
  62443. get: function () {
  62444. if (typeof DracoDecoderModule !== "undefined") {
  62445. return true;
  62446. }
  62447. var decoder = DracoCompression.Configuration.decoder;
  62448. if (decoder) {
  62449. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62450. return true;
  62451. }
  62452. if (decoder.fallbackUrl) {
  62453. return true;
  62454. }
  62455. }
  62456. return false;
  62457. },
  62458. enumerable: true,
  62459. configurable: true
  62460. });
  62461. /**
  62462. * Stop all async operations and release resources.
  62463. */
  62464. DracoCompression.prototype.dispose = function () {
  62465. };
  62466. /**
  62467. * Decode Draco compressed mesh data to vertex data.
  62468. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62469. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62470. * @returns A promise that resolves with the decoded vertex data
  62471. */
  62472. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62473. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62474. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62475. var module = wrappedModule.module;
  62476. var vertexData = new BABYLON.VertexData();
  62477. var buffer = new module.DecoderBuffer();
  62478. buffer.Init(dataView, dataView.byteLength);
  62479. var decoder = new module.Decoder();
  62480. var geometry;
  62481. var status;
  62482. try {
  62483. var type = decoder.GetEncodedGeometryType(buffer);
  62484. switch (type) {
  62485. case module.TRIANGULAR_MESH:
  62486. geometry = new module.Mesh();
  62487. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62488. break;
  62489. case module.POINT_CLOUD:
  62490. geometry = new module.PointCloud();
  62491. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62492. break;
  62493. default:
  62494. throw new Error("Invalid geometry type " + type);
  62495. }
  62496. if (!status.ok() || !geometry.ptr) {
  62497. throw new Error(status.error_msg());
  62498. }
  62499. var numPoints = geometry.num_points();
  62500. if (type === module.TRIANGULAR_MESH) {
  62501. var numFaces = geometry.num_faces();
  62502. var faceIndices = new module.DracoInt32Array();
  62503. try {
  62504. var indices = new Uint32Array(numFaces * 3);
  62505. for (var i = 0; i < numFaces; i++) {
  62506. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62507. var offset = i * 3;
  62508. indices[offset + 0] = faceIndices.GetValue(0);
  62509. indices[offset + 1] = faceIndices.GetValue(1);
  62510. indices[offset + 2] = faceIndices.GetValue(2);
  62511. }
  62512. vertexData.indices = indices;
  62513. }
  62514. finally {
  62515. module.destroy(faceIndices);
  62516. }
  62517. }
  62518. for (var kind in attributes) {
  62519. var uniqueId = attributes[kind];
  62520. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62521. var dracoData = new module.DracoFloat32Array();
  62522. try {
  62523. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62524. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62525. for (var i = 0; i < babylonData.length; i++) {
  62526. babylonData[i] = dracoData.GetValue(i);
  62527. }
  62528. vertexData.set(babylonData, kind);
  62529. }
  62530. finally {
  62531. module.destroy(dracoData);
  62532. }
  62533. }
  62534. }
  62535. finally {
  62536. if (geometry) {
  62537. module.destroy(geometry);
  62538. }
  62539. module.destroy(decoder);
  62540. module.destroy(buffer);
  62541. }
  62542. return vertexData;
  62543. });
  62544. };
  62545. DracoCompression._GetDecoderModule = function () {
  62546. if (!DracoCompression._DecoderModulePromise) {
  62547. var promise = null;
  62548. var config_1 = {};
  62549. if (typeof DracoDecoderModule !== "undefined") {
  62550. promise = Promise.resolve();
  62551. }
  62552. else {
  62553. var decoder = DracoCompression.Configuration.decoder;
  62554. if (decoder) {
  62555. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62556. promise = Promise.all([
  62557. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62558. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62559. config_1.wasmBinary = data;
  62560. })
  62561. ]);
  62562. }
  62563. else if (decoder.fallbackUrl) {
  62564. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62565. }
  62566. }
  62567. }
  62568. if (!promise) {
  62569. throw new Error("Draco decoder module is not available");
  62570. }
  62571. DracoCompression._DecoderModulePromise = promise.then(function () {
  62572. return new Promise(function (resolve) {
  62573. config_1.onModuleLoaded = function (decoderModule) {
  62574. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62575. resolve({ module: decoderModule });
  62576. };
  62577. DracoDecoderModule(config_1);
  62578. });
  62579. });
  62580. }
  62581. return DracoCompression._DecoderModulePromise;
  62582. };
  62583. DracoCompression._LoadScriptAsync = function (url) {
  62584. return new Promise(function (resolve, reject) {
  62585. BABYLON.Tools.LoadScript(url, function () {
  62586. resolve();
  62587. }, function (message) {
  62588. reject(new Error(message));
  62589. });
  62590. });
  62591. };
  62592. DracoCompression._LoadFileAsync = function (url) {
  62593. return new Promise(function (resolve, reject) {
  62594. BABYLON.Tools.LoadFile(url, function (data) {
  62595. resolve(data);
  62596. }, undefined, undefined, true, function (request, exception) {
  62597. reject(exception);
  62598. });
  62599. });
  62600. };
  62601. /**
  62602. * The configuration. Defaults to the following urls:
  62603. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62604. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62605. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62606. */
  62607. DracoCompression.Configuration = {
  62608. decoder: {
  62609. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62610. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62611. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62612. }
  62613. };
  62614. return DracoCompression;
  62615. }());
  62616. BABYLON.DracoCompression = DracoCompression;
  62617. })(BABYLON || (BABYLON = {}));
  62618. //# sourceMappingURL=babylon.dracoCompression.js.map
  62619. var BABYLON;
  62620. (function (BABYLON) {
  62621. var AudioEngine = /** @class */ (function () {
  62622. function AudioEngine() {
  62623. this._audioContext = null;
  62624. this._audioContextInitialized = false;
  62625. this.canUseWebAudio = false;
  62626. this.WarnedWebAudioUnsupported = false;
  62627. this.unlocked = false;
  62628. this.isMP3supported = false;
  62629. this.isOGGsupported = false;
  62630. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62631. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62632. this.canUseWebAudio = true;
  62633. }
  62634. var audioElem = document.createElement('audio');
  62635. try {
  62636. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62637. this.isMP3supported = true;
  62638. }
  62639. }
  62640. catch (e) {
  62641. // protect error during capability check.
  62642. }
  62643. try {
  62644. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62645. this.isOGGsupported = true;
  62646. }
  62647. }
  62648. catch (e) {
  62649. // protect error during capability check.
  62650. }
  62651. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62652. this._unlockiOSaudio();
  62653. }
  62654. else {
  62655. this.unlocked = true;
  62656. }
  62657. }
  62658. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62659. get: function () {
  62660. if (!this._audioContextInitialized) {
  62661. this._initializeAudioContext();
  62662. }
  62663. return this._audioContext;
  62664. },
  62665. enumerable: true,
  62666. configurable: true
  62667. });
  62668. AudioEngine.prototype._unlockiOSaudio = function () {
  62669. var _this = this;
  62670. var unlockaudio = function () {
  62671. if (!_this.audioContext) {
  62672. return;
  62673. }
  62674. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62675. var source = _this.audioContext.createBufferSource();
  62676. source.buffer = buffer;
  62677. source.connect(_this.audioContext.destination);
  62678. source.start(0);
  62679. setTimeout(function () {
  62680. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62681. _this.unlocked = true;
  62682. window.removeEventListener('touchend', unlockaudio, false);
  62683. if (_this.onAudioUnlocked) {
  62684. _this.onAudioUnlocked();
  62685. }
  62686. }
  62687. }, 0);
  62688. };
  62689. window.addEventListener('touchend', unlockaudio, false);
  62690. };
  62691. AudioEngine.prototype._initializeAudioContext = function () {
  62692. try {
  62693. if (this.canUseWebAudio) {
  62694. this._audioContext = new AudioContext();
  62695. // create a global volume gain node
  62696. this.masterGain = this._audioContext.createGain();
  62697. this.masterGain.gain.value = 1;
  62698. this.masterGain.connect(this._audioContext.destination);
  62699. this._audioContextInitialized = true;
  62700. }
  62701. }
  62702. catch (e) {
  62703. this.canUseWebAudio = false;
  62704. BABYLON.Tools.Error("Web Audio: " + e.message);
  62705. }
  62706. };
  62707. AudioEngine.prototype.dispose = function () {
  62708. if (this.canUseWebAudio && this._audioContextInitialized) {
  62709. if (this._connectedAnalyser && this._audioContext) {
  62710. this._connectedAnalyser.stopDebugCanvas();
  62711. this._connectedAnalyser.dispose();
  62712. this.masterGain.disconnect();
  62713. this.masterGain.connect(this._audioContext.destination);
  62714. this._connectedAnalyser = null;
  62715. }
  62716. this.masterGain.gain.value = 1;
  62717. }
  62718. this.WarnedWebAudioUnsupported = false;
  62719. };
  62720. AudioEngine.prototype.getGlobalVolume = function () {
  62721. if (this.canUseWebAudio && this._audioContextInitialized) {
  62722. return this.masterGain.gain.value;
  62723. }
  62724. else {
  62725. return -1;
  62726. }
  62727. };
  62728. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62729. if (this.canUseWebAudio && this._audioContextInitialized) {
  62730. this.masterGain.gain.value = newVolume;
  62731. }
  62732. };
  62733. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62734. if (this._connectedAnalyser) {
  62735. this._connectedAnalyser.stopDebugCanvas();
  62736. }
  62737. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62738. this._connectedAnalyser = analyser;
  62739. this.masterGain.disconnect();
  62740. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62741. }
  62742. };
  62743. return AudioEngine;
  62744. }());
  62745. BABYLON.AudioEngine = AudioEngine;
  62746. })(BABYLON || (BABYLON = {}));
  62747. //# sourceMappingURL=babylon.audioEngine.js.map
  62748. var BABYLON;
  62749. (function (BABYLON) {
  62750. var Sound = /** @class */ (function () {
  62751. /**
  62752. * Create a sound and attach it to a scene
  62753. * @param name Name of your sound
  62754. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62755. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62756. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62757. */
  62758. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62759. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62760. var _this = this;
  62761. this.autoplay = false;
  62762. this.loop = false;
  62763. this.useCustomAttenuation = false;
  62764. this.spatialSound = false;
  62765. this.refDistance = 1;
  62766. this.rolloffFactor = 1;
  62767. this.maxDistance = 100;
  62768. this.distanceModel = "linear";
  62769. this._panningModel = "equalpower";
  62770. this._playbackRate = 1;
  62771. this._streaming = false;
  62772. this._startTime = 0;
  62773. this._startOffset = 0;
  62774. this._position = BABYLON.Vector3.Zero();
  62775. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62776. this._volume = 1;
  62777. this._isReadyToPlay = false;
  62778. this.isPlaying = false;
  62779. this.isPaused = false;
  62780. this._isDirectional = false;
  62781. // Used if you'd like to create a directional sound.
  62782. // If not set, the sound will be omnidirectional
  62783. this._coneInnerAngle = 360;
  62784. this._coneOuterAngle = 360;
  62785. this._coneOuterGain = 0;
  62786. this._isOutputConnected = false;
  62787. this._urlType = "Unknown";
  62788. this.name = name;
  62789. this._scene = scene;
  62790. this._readyToPlayCallback = readyToPlayCallback;
  62791. // Default custom attenuation function is a linear attenuation
  62792. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62793. if (currentDistance < maxDistance) {
  62794. return currentVolume * (1 - currentDistance / maxDistance);
  62795. }
  62796. else {
  62797. return 0;
  62798. }
  62799. };
  62800. if (options) {
  62801. this.autoplay = options.autoplay || false;
  62802. this.loop = options.loop || false;
  62803. // if volume === 0, we need another way to check this option
  62804. if (options.volume !== undefined) {
  62805. this._volume = options.volume;
  62806. }
  62807. this.spatialSound = options.spatialSound || false;
  62808. this.maxDistance = options.maxDistance || 100;
  62809. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62810. this.rolloffFactor = options.rolloffFactor || 1;
  62811. this.refDistance = options.refDistance || 1;
  62812. this.distanceModel = options.distanceModel || "linear";
  62813. this._playbackRate = options.playbackRate || 1;
  62814. this._streaming = options.streaming || false;
  62815. }
  62816. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62817. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62818. this._soundGain.gain.value = this._volume;
  62819. this._inputAudioNode = this._soundGain;
  62820. this._ouputAudioNode = this._soundGain;
  62821. if (this.spatialSound) {
  62822. this._createSpatialParameters();
  62823. }
  62824. this._scene.mainSoundTrack.AddSound(this);
  62825. var validParameter = true;
  62826. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62827. if (urlOrArrayBuffer) {
  62828. try {
  62829. if (typeof (urlOrArrayBuffer) === "string")
  62830. this._urlType = "String";
  62831. if (Array.isArray(urlOrArrayBuffer))
  62832. this._urlType = "Array";
  62833. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62834. this._urlType = "ArrayBuffer";
  62835. var urls = [];
  62836. var codecSupportedFound = false;
  62837. switch (this._urlType) {
  62838. case "ArrayBuffer":
  62839. if (urlOrArrayBuffer.byteLength > 0) {
  62840. codecSupportedFound = true;
  62841. this._soundLoaded(urlOrArrayBuffer);
  62842. }
  62843. break;
  62844. case "String":
  62845. urls.push(urlOrArrayBuffer);
  62846. case "Array":
  62847. if (urls.length === 0)
  62848. urls = urlOrArrayBuffer;
  62849. // If we found a supported format, we load it immediately and stop the loop
  62850. for (var i = 0; i < urls.length; i++) {
  62851. var url = urls[i];
  62852. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62853. codecSupportedFound = true;
  62854. }
  62855. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62856. codecSupportedFound = true;
  62857. }
  62858. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62859. codecSupportedFound = true;
  62860. }
  62861. if (url.indexOf("blob:") !== -1) {
  62862. codecSupportedFound = true;
  62863. }
  62864. if (codecSupportedFound) {
  62865. // Loading sound using XHR2
  62866. if (!this._streaming) {
  62867. this._scene._loadFile(url, function (data) {
  62868. _this._soundLoaded(data);
  62869. }, undefined, true, true, function (exception) {
  62870. if (exception) {
  62871. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62872. }
  62873. BABYLON.Tools.Error("Sound creation aborted.");
  62874. _this._scene.mainSoundTrack.RemoveSound(_this);
  62875. });
  62876. }
  62877. // Streaming sound using HTML5 Audio tag
  62878. else {
  62879. this._htmlAudioElement = new Audio(url);
  62880. this._htmlAudioElement.controls = false;
  62881. this._htmlAudioElement.loop = this.loop;
  62882. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62883. this._htmlAudioElement.preload = "auto";
  62884. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62885. _this._isReadyToPlay = true;
  62886. if (_this.autoplay) {
  62887. _this.play();
  62888. }
  62889. if (_this._readyToPlayCallback) {
  62890. _this._readyToPlayCallback();
  62891. }
  62892. });
  62893. document.body.appendChild(this._htmlAudioElement);
  62894. }
  62895. break;
  62896. }
  62897. }
  62898. break;
  62899. default:
  62900. validParameter = false;
  62901. break;
  62902. }
  62903. if (!validParameter) {
  62904. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62905. }
  62906. else {
  62907. if (!codecSupportedFound) {
  62908. this._isReadyToPlay = true;
  62909. // Simulating a ready to play event to avoid breaking code path
  62910. if (this._readyToPlayCallback) {
  62911. window.setTimeout(function () {
  62912. if (_this._readyToPlayCallback) {
  62913. _this._readyToPlayCallback();
  62914. }
  62915. }, 1000);
  62916. }
  62917. }
  62918. }
  62919. }
  62920. catch (ex) {
  62921. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62922. this._scene.mainSoundTrack.RemoveSound(this);
  62923. }
  62924. }
  62925. }
  62926. else {
  62927. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62928. this._scene.mainSoundTrack.AddSound(this);
  62929. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62930. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62931. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62932. }
  62933. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62934. if (this._readyToPlayCallback) {
  62935. window.setTimeout(function () {
  62936. if (_this._readyToPlayCallback) {
  62937. _this._readyToPlayCallback();
  62938. }
  62939. }, 1000);
  62940. }
  62941. }
  62942. }
  62943. Sound.prototype.dispose = function () {
  62944. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62945. if (this.isPlaying) {
  62946. this.stop();
  62947. }
  62948. this._isReadyToPlay = false;
  62949. if (this.soundTrackId === -1) {
  62950. this._scene.mainSoundTrack.RemoveSound(this);
  62951. }
  62952. else {
  62953. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62954. }
  62955. if (this._soundGain) {
  62956. this._soundGain.disconnect();
  62957. this._soundGain = null;
  62958. }
  62959. if (this._soundPanner) {
  62960. this._soundPanner.disconnect();
  62961. this._soundPanner = null;
  62962. }
  62963. if (this._soundSource) {
  62964. this._soundSource.disconnect();
  62965. this._soundSource = null;
  62966. }
  62967. this._audioBuffer = null;
  62968. if (this._htmlAudioElement) {
  62969. this._htmlAudioElement.pause();
  62970. this._htmlAudioElement.src = "";
  62971. document.body.removeChild(this._htmlAudioElement);
  62972. }
  62973. if (this._connectedMesh && this._registerFunc) {
  62974. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62975. this._connectedMesh = null;
  62976. }
  62977. }
  62978. };
  62979. Sound.prototype.isReady = function () {
  62980. return this._isReadyToPlay;
  62981. };
  62982. Sound.prototype._soundLoaded = function (audioData) {
  62983. var _this = this;
  62984. if (!BABYLON.Engine.audioEngine.audioContext) {
  62985. return;
  62986. }
  62987. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62988. _this._audioBuffer = buffer;
  62989. _this._isReadyToPlay = true;
  62990. if (_this.autoplay) {
  62991. _this.play();
  62992. }
  62993. if (_this._readyToPlayCallback) {
  62994. _this._readyToPlayCallback();
  62995. }
  62996. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62997. };
  62998. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62999. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63000. this._audioBuffer = audioBuffer;
  63001. this._isReadyToPlay = true;
  63002. }
  63003. };
  63004. Sound.prototype.updateOptions = function (options) {
  63005. if (options) {
  63006. this.loop = options.loop || this.loop;
  63007. this.maxDistance = options.maxDistance || this.maxDistance;
  63008. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  63009. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  63010. this.refDistance = options.refDistance || this.refDistance;
  63011. this.distanceModel = options.distanceModel || this.distanceModel;
  63012. this._playbackRate = options.playbackRate || this._playbackRate;
  63013. this._updateSpatialParameters();
  63014. if (this.isPlaying) {
  63015. if (this._streaming) {
  63016. this._htmlAudioElement.playbackRate = this._playbackRate;
  63017. }
  63018. else {
  63019. if (this._soundSource) {
  63020. this._soundSource.playbackRate.value = this._playbackRate;
  63021. }
  63022. }
  63023. }
  63024. }
  63025. };
  63026. Sound.prototype._createSpatialParameters = function () {
  63027. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63028. if (this._scene.headphone) {
  63029. this._panningModel = "HRTF";
  63030. }
  63031. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  63032. this._updateSpatialParameters();
  63033. this._soundPanner.connect(this._ouputAudioNode);
  63034. this._inputAudioNode = this._soundPanner;
  63035. }
  63036. };
  63037. Sound.prototype._updateSpatialParameters = function () {
  63038. if (this.spatialSound && this._soundPanner) {
  63039. if (this.useCustomAttenuation) {
  63040. // Tricks to disable in a way embedded Web Audio attenuation
  63041. this._soundPanner.distanceModel = "linear";
  63042. this._soundPanner.maxDistance = Number.MAX_VALUE;
  63043. this._soundPanner.refDistance = 1;
  63044. this._soundPanner.rolloffFactor = 1;
  63045. this._soundPanner.panningModel = this._panningModel;
  63046. }
  63047. else {
  63048. this._soundPanner.distanceModel = this.distanceModel;
  63049. this._soundPanner.maxDistance = this.maxDistance;
  63050. this._soundPanner.refDistance = this.refDistance;
  63051. this._soundPanner.rolloffFactor = this.rolloffFactor;
  63052. this._soundPanner.panningModel = this._panningModel;
  63053. }
  63054. }
  63055. };
  63056. Sound.prototype.switchPanningModelToHRTF = function () {
  63057. this._panningModel = "HRTF";
  63058. this._switchPanningModel();
  63059. };
  63060. Sound.prototype.switchPanningModelToEqualPower = function () {
  63061. this._panningModel = "equalpower";
  63062. this._switchPanningModel();
  63063. };
  63064. Sound.prototype._switchPanningModel = function () {
  63065. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63066. this._soundPanner.panningModel = this._panningModel;
  63067. }
  63068. };
  63069. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  63070. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63071. if (this._isOutputConnected) {
  63072. this._ouputAudioNode.disconnect();
  63073. }
  63074. this._ouputAudioNode.connect(soundTrackAudioNode);
  63075. this._isOutputConnected = true;
  63076. }
  63077. };
  63078. /**
  63079. * Transform this sound into a directional source
  63080. * @param coneInnerAngle Size of the inner cone in degree
  63081. * @param coneOuterAngle Size of the outer cone in degree
  63082. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63083. */
  63084. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63085. if (coneOuterAngle < coneInnerAngle) {
  63086. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63087. return;
  63088. }
  63089. this._coneInnerAngle = coneInnerAngle;
  63090. this._coneOuterAngle = coneOuterAngle;
  63091. this._coneOuterGain = coneOuterGain;
  63092. this._isDirectional = true;
  63093. if (this.isPlaying && this.loop) {
  63094. this.stop();
  63095. this.play();
  63096. }
  63097. };
  63098. Sound.prototype.setPosition = function (newPosition) {
  63099. this._position = newPosition;
  63100. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63101. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63102. }
  63103. };
  63104. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63105. this._localDirection = newLocalDirection;
  63106. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63107. this._updateDirection();
  63108. }
  63109. };
  63110. Sound.prototype._updateDirection = function () {
  63111. if (!this._connectedMesh || !this._soundPanner) {
  63112. return;
  63113. }
  63114. var mat = this._connectedMesh.getWorldMatrix();
  63115. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63116. direction.normalize();
  63117. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63118. };
  63119. Sound.prototype.updateDistanceFromListener = function () {
  63120. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  63121. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  63122. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  63123. }
  63124. };
  63125. Sound.prototype.setAttenuationFunction = function (callback) {
  63126. this._customAttenuationFunction = callback;
  63127. };
  63128. /**
  63129. * Play the sound
  63130. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  63131. * @param offset (optional) Start the sound setting it at a specific time
  63132. */
  63133. Sound.prototype.play = function (time, offset) {
  63134. var _this = this;
  63135. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  63136. try {
  63137. if (this._startOffset < 0) {
  63138. time = -this._startOffset;
  63139. this._startOffset = 0;
  63140. }
  63141. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63142. if (!this._soundSource || !this._streamingSource) {
  63143. if (this.spatialSound && this._soundPanner) {
  63144. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63145. if (this._isDirectional) {
  63146. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  63147. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  63148. this._soundPanner.coneOuterGain = this._coneOuterGain;
  63149. if (this._connectedMesh) {
  63150. this._updateDirection();
  63151. }
  63152. else {
  63153. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  63154. }
  63155. }
  63156. }
  63157. }
  63158. if (this._streaming) {
  63159. if (!this._streamingSource) {
  63160. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63161. this._htmlAudioElement.onended = function () { _this._onended(); };
  63162. this._htmlAudioElement.playbackRate = this._playbackRate;
  63163. }
  63164. this._streamingSource.disconnect();
  63165. this._streamingSource.connect(this._inputAudioNode);
  63166. this._htmlAudioElement.play();
  63167. }
  63168. else {
  63169. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63170. this._soundSource.buffer = this._audioBuffer;
  63171. this._soundSource.connect(this._inputAudioNode);
  63172. this._soundSource.loop = this.loop;
  63173. this._soundSource.playbackRate.value = this._playbackRate;
  63174. this._soundSource.onended = function () { _this._onended(); };
  63175. if (this._soundSource.buffer) {
  63176. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63177. }
  63178. }
  63179. this._startTime = startTime;
  63180. this.isPlaying = true;
  63181. this.isPaused = false;
  63182. }
  63183. catch (ex) {
  63184. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63185. }
  63186. }
  63187. };
  63188. Sound.prototype._onended = function () {
  63189. this.isPlaying = false;
  63190. if (this.onended) {
  63191. this.onended();
  63192. }
  63193. };
  63194. /**
  63195. * Stop the sound
  63196. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63197. */
  63198. Sound.prototype.stop = function (time) {
  63199. if (this.isPlaying) {
  63200. if (this._streaming) {
  63201. this._htmlAudioElement.pause();
  63202. // Test needed for Firefox or it will generate an Invalid State Error
  63203. if (this._htmlAudioElement.currentTime > 0) {
  63204. this._htmlAudioElement.currentTime = 0;
  63205. }
  63206. }
  63207. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63208. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63209. this._soundSource.stop(stopTime);
  63210. this._soundSource.onended = function () { };
  63211. if (!this.isPaused) {
  63212. this._startOffset = 0;
  63213. }
  63214. }
  63215. this.isPlaying = false;
  63216. }
  63217. };
  63218. Sound.prototype.pause = function () {
  63219. if (this.isPlaying) {
  63220. this.isPaused = true;
  63221. if (this._streaming) {
  63222. this._htmlAudioElement.pause();
  63223. }
  63224. else if (BABYLON.Engine.audioEngine.audioContext) {
  63225. this.stop(0);
  63226. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63227. }
  63228. }
  63229. };
  63230. Sound.prototype.setVolume = function (newVolume, time) {
  63231. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63232. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63233. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63234. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63235. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63236. }
  63237. else {
  63238. this._soundGain.gain.value = newVolume;
  63239. }
  63240. }
  63241. this._volume = newVolume;
  63242. };
  63243. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63244. this._playbackRate = newPlaybackRate;
  63245. if (this.isPlaying) {
  63246. if (this._streaming) {
  63247. this._htmlAudioElement.playbackRate = this._playbackRate;
  63248. }
  63249. else if (this._soundSource) {
  63250. this._soundSource.playbackRate.value = this._playbackRate;
  63251. }
  63252. }
  63253. };
  63254. Sound.prototype.getVolume = function () {
  63255. return this._volume;
  63256. };
  63257. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63258. var _this = this;
  63259. if (this._connectedMesh && this._registerFunc) {
  63260. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63261. this._registerFunc = null;
  63262. }
  63263. this._connectedMesh = meshToConnectTo;
  63264. if (!this.spatialSound) {
  63265. this.spatialSound = true;
  63266. this._createSpatialParameters();
  63267. if (this.isPlaying && this.loop) {
  63268. this.stop();
  63269. this.play();
  63270. }
  63271. }
  63272. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63273. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63274. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63275. };
  63276. Sound.prototype.detachFromMesh = function () {
  63277. if (this._connectedMesh && this._registerFunc) {
  63278. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63279. this._registerFunc = null;
  63280. this._connectedMesh = null;
  63281. }
  63282. };
  63283. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63284. if (!node.getBoundingInfo) {
  63285. return;
  63286. }
  63287. var mesh = node;
  63288. var boundingInfo = mesh.getBoundingInfo();
  63289. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63291. this._updateDirection();
  63292. }
  63293. };
  63294. Sound.prototype.clone = function () {
  63295. var _this = this;
  63296. if (!this._streaming) {
  63297. var setBufferAndRun = function () {
  63298. if (_this._isReadyToPlay) {
  63299. clonedSound._audioBuffer = _this.getAudioBuffer();
  63300. clonedSound._isReadyToPlay = true;
  63301. if (clonedSound.autoplay) {
  63302. clonedSound.play();
  63303. }
  63304. }
  63305. else {
  63306. window.setTimeout(setBufferAndRun, 300);
  63307. }
  63308. };
  63309. var currentOptions = {
  63310. autoplay: this.autoplay, loop: this.loop,
  63311. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63312. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63313. refDistance: this.refDistance, distanceModel: this.distanceModel
  63314. };
  63315. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63316. if (this.useCustomAttenuation) {
  63317. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63318. }
  63319. clonedSound.setPosition(this._position);
  63320. clonedSound.setPlaybackRate(this._playbackRate);
  63321. setBufferAndRun();
  63322. return clonedSound;
  63323. }
  63324. // Can't clone a streaming sound
  63325. else {
  63326. return null;
  63327. }
  63328. };
  63329. Sound.prototype.getAudioBuffer = function () {
  63330. return this._audioBuffer;
  63331. };
  63332. Sound.prototype.serialize = function () {
  63333. var serializationObject = {
  63334. name: this.name,
  63335. url: this.name,
  63336. autoplay: this.autoplay,
  63337. loop: this.loop,
  63338. volume: this._volume,
  63339. spatialSound: this.spatialSound,
  63340. maxDistance: this.maxDistance,
  63341. rolloffFactor: this.rolloffFactor,
  63342. refDistance: this.refDistance,
  63343. distanceModel: this.distanceModel,
  63344. playbackRate: this._playbackRate,
  63345. panningModel: this._panningModel,
  63346. soundTrackId: this.soundTrackId
  63347. };
  63348. if (this.spatialSound) {
  63349. if (this._connectedMesh)
  63350. serializationObject.connectedMeshId = this._connectedMesh.id;
  63351. serializationObject.position = this._position.asArray();
  63352. serializationObject.refDistance = this.refDistance;
  63353. serializationObject.distanceModel = this.distanceModel;
  63354. serializationObject.isDirectional = this._isDirectional;
  63355. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63356. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63357. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63358. serializationObject.coneOuterGain = this._coneOuterGain;
  63359. }
  63360. return serializationObject;
  63361. };
  63362. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63363. var soundName = parsedSound.name;
  63364. var soundUrl;
  63365. if (parsedSound.url) {
  63366. soundUrl = rootUrl + parsedSound.url;
  63367. }
  63368. else {
  63369. soundUrl = rootUrl + soundName;
  63370. }
  63371. var options = {
  63372. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63373. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63374. rolloffFactor: parsedSound.rolloffFactor,
  63375. refDistance: parsedSound.refDistance,
  63376. distanceModel: parsedSound.distanceModel,
  63377. playbackRate: parsedSound.playbackRate
  63378. };
  63379. var newSound;
  63380. if (!sourceSound) {
  63381. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63382. scene._addPendingData(newSound);
  63383. }
  63384. else {
  63385. var setBufferAndRun = function () {
  63386. if (sourceSound._isReadyToPlay) {
  63387. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63388. newSound._isReadyToPlay = true;
  63389. if (newSound.autoplay) {
  63390. newSound.play();
  63391. }
  63392. }
  63393. else {
  63394. window.setTimeout(setBufferAndRun, 300);
  63395. }
  63396. };
  63397. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63398. setBufferAndRun();
  63399. }
  63400. if (parsedSound.position) {
  63401. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63402. newSound.setPosition(soundPosition);
  63403. }
  63404. if (parsedSound.isDirectional) {
  63405. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63406. if (parsedSound.localDirectionToMesh) {
  63407. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63408. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63409. }
  63410. }
  63411. if (parsedSound.connectedMeshId) {
  63412. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63413. if (connectedMesh) {
  63414. newSound.attachToMesh(connectedMesh);
  63415. }
  63416. }
  63417. return newSound;
  63418. };
  63419. return Sound;
  63420. }());
  63421. BABYLON.Sound = Sound;
  63422. })(BABYLON || (BABYLON = {}));
  63423. //# sourceMappingURL=babylon.sound.js.map
  63424. var BABYLON;
  63425. (function (BABYLON) {
  63426. var SoundTrack = /** @class */ (function () {
  63427. function SoundTrack(scene, options) {
  63428. this.id = -1;
  63429. this._isMainTrack = false;
  63430. this._isInitialized = false;
  63431. this._scene = scene;
  63432. this.soundCollection = new Array();
  63433. this._options = options;
  63434. if (!this._isMainTrack) {
  63435. this._scene.soundTracks.push(this);
  63436. this.id = this._scene.soundTracks.length - 1;
  63437. }
  63438. }
  63439. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63440. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63441. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63442. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63443. if (this._options) {
  63444. if (this._options.volume) {
  63445. this._outputAudioNode.gain.value = this._options.volume;
  63446. }
  63447. if (this._options.mainTrack) {
  63448. this._isMainTrack = this._options.mainTrack;
  63449. }
  63450. }
  63451. this._isInitialized = true;
  63452. }
  63453. };
  63454. SoundTrack.prototype.dispose = function () {
  63455. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63456. if (this._connectedAnalyser) {
  63457. this._connectedAnalyser.stopDebugCanvas();
  63458. }
  63459. while (this.soundCollection.length) {
  63460. this.soundCollection[0].dispose();
  63461. }
  63462. if (this._outputAudioNode) {
  63463. this._outputAudioNode.disconnect();
  63464. }
  63465. this._outputAudioNode = null;
  63466. }
  63467. };
  63468. SoundTrack.prototype.AddSound = function (sound) {
  63469. if (!this._isInitialized) {
  63470. this._initializeSoundTrackAudioGraph();
  63471. }
  63472. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63473. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63474. }
  63475. if (sound.soundTrackId) {
  63476. if (sound.soundTrackId === -1) {
  63477. this._scene.mainSoundTrack.RemoveSound(sound);
  63478. }
  63479. else {
  63480. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63481. }
  63482. }
  63483. this.soundCollection.push(sound);
  63484. sound.soundTrackId = this.id;
  63485. };
  63486. SoundTrack.prototype.RemoveSound = function (sound) {
  63487. var index = this.soundCollection.indexOf(sound);
  63488. if (index !== -1) {
  63489. this.soundCollection.splice(index, 1);
  63490. }
  63491. };
  63492. SoundTrack.prototype.setVolume = function (newVolume) {
  63493. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63494. this._outputAudioNode.gain.value = newVolume;
  63495. }
  63496. };
  63497. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63498. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63499. for (var i = 0; i < this.soundCollection.length; i++) {
  63500. this.soundCollection[i].switchPanningModelToHRTF();
  63501. }
  63502. }
  63503. };
  63504. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63505. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63506. for (var i = 0; i < this.soundCollection.length; i++) {
  63507. this.soundCollection[i].switchPanningModelToEqualPower();
  63508. }
  63509. }
  63510. };
  63511. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63512. if (this._connectedAnalyser) {
  63513. this._connectedAnalyser.stopDebugCanvas();
  63514. }
  63515. this._connectedAnalyser = analyser;
  63516. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63517. this._outputAudioNode.disconnect();
  63518. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63519. }
  63520. };
  63521. return SoundTrack;
  63522. }());
  63523. BABYLON.SoundTrack = SoundTrack;
  63524. })(BABYLON || (BABYLON = {}));
  63525. //# sourceMappingURL=babylon.soundtrack.js.map
  63526. var BABYLON;
  63527. (function (BABYLON) {
  63528. /**
  63529. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63530. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63531. */
  63532. var Analyser = /** @class */ (function () {
  63533. /**
  63534. * Creates a new analyser
  63535. * @param scene defines hosting scene
  63536. */
  63537. function Analyser(scene) {
  63538. /**
  63539. * Gets or sets the smoothing
  63540. * @ignorenaming
  63541. */
  63542. this.SMOOTHING = 0.75;
  63543. /**
  63544. * Gets or sets the FFT table size
  63545. * @ignorenaming
  63546. */
  63547. this.FFT_SIZE = 512;
  63548. /**
  63549. * Gets or sets the bar graph amplitude
  63550. * @ignorenaming
  63551. */
  63552. this.BARGRAPHAMPLITUDE = 256;
  63553. /**
  63554. * Gets or sets the position of the debug canvas
  63555. * @ignorenaming
  63556. */
  63557. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63558. /**
  63559. * Gets or sets the debug canvas size
  63560. * @ignorenaming
  63561. */
  63562. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63563. this._scene = scene;
  63564. this._audioEngine = BABYLON.Engine.audioEngine;
  63565. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63566. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63567. this._webAudioAnalyser.minDecibels = -140;
  63568. this._webAudioAnalyser.maxDecibels = 0;
  63569. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63570. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63571. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63572. }
  63573. }
  63574. /**
  63575. * Get the number of data values you will have to play with for the visualization
  63576. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63577. * @returns a number
  63578. */
  63579. Analyser.prototype.getFrequencyBinCount = function () {
  63580. if (this._audioEngine.canUseWebAudio) {
  63581. return this._webAudioAnalyser.frequencyBinCount;
  63582. }
  63583. else {
  63584. return 0;
  63585. }
  63586. };
  63587. /**
  63588. * Gets the current frequency data as a byte array
  63589. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63590. * @returns a Uint8Array
  63591. */
  63592. Analyser.prototype.getByteFrequencyData = function () {
  63593. if (this._audioEngine.canUseWebAudio) {
  63594. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63595. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63596. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63597. }
  63598. return this._byteFreqs;
  63599. };
  63600. /**
  63601. * Gets the current waveform as a byte array
  63602. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63603. * @returns a Uint8Array
  63604. */
  63605. Analyser.prototype.getByteTimeDomainData = function () {
  63606. if (this._audioEngine.canUseWebAudio) {
  63607. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63608. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63609. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63610. }
  63611. return this._byteTime;
  63612. };
  63613. /**
  63614. * Gets the current frequency data as a float array
  63615. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63616. * @returns a Float32Array
  63617. */
  63618. Analyser.prototype.getFloatFrequencyData = function () {
  63619. if (this._audioEngine.canUseWebAudio) {
  63620. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63621. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63622. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63623. }
  63624. return this._floatFreqs;
  63625. };
  63626. /**
  63627. * Renders the debug canvas
  63628. */
  63629. Analyser.prototype.drawDebugCanvas = function () {
  63630. var _this = this;
  63631. if (this._audioEngine.canUseWebAudio) {
  63632. if (!this._debugCanvas) {
  63633. this._debugCanvas = document.createElement("canvas");
  63634. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63635. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63636. this._debugCanvas.style.position = "absolute";
  63637. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63638. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63639. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63640. document.body.appendChild(this._debugCanvas);
  63641. this._registerFunc = function () {
  63642. _this.drawDebugCanvas();
  63643. };
  63644. this._scene.registerBeforeRender(this._registerFunc);
  63645. }
  63646. if (this._registerFunc && this._debugCanvasContext) {
  63647. var workingArray = this.getByteFrequencyData();
  63648. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63649. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63650. // Draw the frequency domain chart.
  63651. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63652. var value = workingArray[i];
  63653. var percent = value / this.BARGRAPHAMPLITUDE;
  63654. var height = this.DEBUGCANVASSIZE.height * percent;
  63655. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63656. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63657. var hue = i / this.getFrequencyBinCount() * 360;
  63658. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63659. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63660. }
  63661. }
  63662. }
  63663. };
  63664. /**
  63665. * Stops rendering the debug canvas and removes it
  63666. */
  63667. Analyser.prototype.stopDebugCanvas = function () {
  63668. if (this._debugCanvas) {
  63669. if (this._registerFunc) {
  63670. this._scene.unregisterBeforeRender(this._registerFunc);
  63671. this._registerFunc = null;
  63672. }
  63673. document.body.removeChild(this._debugCanvas);
  63674. this._debugCanvas = null;
  63675. this._debugCanvasContext = null;
  63676. }
  63677. };
  63678. /**
  63679. * Connects two audio nodes
  63680. * @param inputAudioNode defines first node to connect
  63681. * @param outputAudioNode defines second node to connect
  63682. */
  63683. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63684. if (this._audioEngine.canUseWebAudio) {
  63685. inputAudioNode.connect(this._webAudioAnalyser);
  63686. this._webAudioAnalyser.connect(outputAudioNode);
  63687. }
  63688. };
  63689. /**
  63690. * Releases all associated resources
  63691. */
  63692. Analyser.prototype.dispose = function () {
  63693. if (this._audioEngine.canUseWebAudio) {
  63694. this._webAudioAnalyser.disconnect();
  63695. }
  63696. };
  63697. return Analyser;
  63698. }());
  63699. BABYLON.Analyser = Analyser;
  63700. })(BABYLON || (BABYLON = {}));
  63701. //# sourceMappingURL=babylon.analyser.js.map
  63702. var BABYLON;
  63703. (function (BABYLON) {
  63704. var CubeTexture = /** @class */ (function (_super) {
  63705. __extends(CubeTexture, _super);
  63706. /**
  63707. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63708. * as prefiltered data.
  63709. * @param rootUrl defines the url of the texture or the root name of the six images
  63710. * @param scene defines the scene the texture is attached to
  63711. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63712. * @param noMipmap defines if mipmaps should be created or not
  63713. * @param files defines the six files to load for the different faces
  63714. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63715. * @param onError defines a callback triggered in case of error during load
  63716. * @param format defines the internal format to use for the texture once loaded
  63717. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63718. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63719. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63720. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63721. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63722. * @return the cube texture
  63723. */
  63724. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63725. if (extensions === void 0) { extensions = null; }
  63726. if (noMipmap === void 0) { noMipmap = false; }
  63727. if (files === void 0) { files = null; }
  63728. if (onLoad === void 0) { onLoad = null; }
  63729. if (onError === void 0) { onError = null; }
  63730. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63731. if (prefiltered === void 0) { prefiltered = false; }
  63732. if (forcedExtension === void 0) { forcedExtension = null; }
  63733. if (createPolynomials === void 0) { createPolynomials = false; }
  63734. if (lodScale === void 0) { lodScale = 0.8; }
  63735. if (lodOffset === void 0) { lodOffset = 0; }
  63736. var _this = _super.call(this, scene) || this;
  63737. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63738. /**
  63739. * Gets or sets the center of the bounding box associated with the cube texture
  63740. * It must define where the camera used to render the texture was set
  63741. */
  63742. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63743. _this._rotationY = 0;
  63744. /** @hidden */
  63745. _this._prefiltered = false;
  63746. _this.name = rootUrl;
  63747. _this.url = rootUrl;
  63748. _this._noMipmap = noMipmap;
  63749. _this.hasAlpha = false;
  63750. _this._format = format;
  63751. _this.isCube = true;
  63752. _this._textureMatrix = BABYLON.Matrix.Identity();
  63753. _this._createPolynomials = createPolynomials;
  63754. if (!rootUrl && !files) {
  63755. return _this;
  63756. }
  63757. var lastDot = rootUrl.lastIndexOf(".");
  63758. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63759. var isDDS = (extension === ".dds");
  63760. var isEnv = (extension === ".env");
  63761. if (isEnv) {
  63762. _this.gammaSpace = false;
  63763. _this._prefiltered = false;
  63764. }
  63765. else {
  63766. _this._prefiltered = prefiltered;
  63767. if (prefiltered) {
  63768. _this.gammaSpace = false;
  63769. }
  63770. }
  63771. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63772. if (!files) {
  63773. if (!isEnv && !isDDS && !extensions) {
  63774. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63775. }
  63776. files = [];
  63777. if (extensions) {
  63778. for (var index = 0; index < extensions.length; index++) {
  63779. files.push(rootUrl + extensions[index]);
  63780. }
  63781. }
  63782. }
  63783. _this._files = files;
  63784. if (!_this._texture) {
  63785. if (!scene.useDelayedTextureLoading) {
  63786. if (prefiltered) {
  63787. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63788. }
  63789. else {
  63790. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63791. }
  63792. }
  63793. else {
  63794. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63795. }
  63796. }
  63797. else if (onLoad) {
  63798. if (_this._texture.isReady) {
  63799. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63800. }
  63801. else {
  63802. _this._texture.onLoadedObservable.add(onLoad);
  63803. }
  63804. }
  63805. return _this;
  63806. }
  63807. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63808. get: function () {
  63809. return this._boundingBoxSize;
  63810. },
  63811. /**
  63812. * Gets or sets the size of the bounding box associated with the cube texture
  63813. * When defined, the cubemap will switch to local mode
  63814. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63815. * @example https://www.babylonjs-playground.com/#RNASML
  63816. */
  63817. set: function (value) {
  63818. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63819. return;
  63820. }
  63821. this._boundingBoxSize = value;
  63822. var scene = this.getScene();
  63823. if (scene) {
  63824. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63825. }
  63826. },
  63827. enumerable: true,
  63828. configurable: true
  63829. });
  63830. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63831. /**
  63832. * Gets texture matrix rotation angle around Y axis radians.
  63833. */
  63834. get: function () {
  63835. return this._rotationY;
  63836. },
  63837. /**
  63838. * Sets texture matrix rotation angle around Y axis in radians.
  63839. */
  63840. set: function (value) {
  63841. this._rotationY = value;
  63842. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63843. },
  63844. enumerable: true,
  63845. configurable: true
  63846. });
  63847. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63848. var rootUrlKey = "";
  63849. files.forEach(function (url) { return rootUrlKey += url; });
  63850. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63851. };
  63852. /**
  63853. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63854. * @param url defines the url of the prefiltered texture
  63855. * @param scene defines the scene the texture is attached to
  63856. * @param forcedExtension defines the extension of the file if different from the url
  63857. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63858. * @return the prefiltered texture
  63859. */
  63860. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63861. if (forcedExtension === void 0) { forcedExtension = null; }
  63862. if (createPolynomials === void 0) { createPolynomials = true; }
  63863. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63864. };
  63865. // Methods
  63866. CubeTexture.prototype.delayLoad = function () {
  63867. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63868. return;
  63869. }
  63870. var scene = this.getScene();
  63871. if (!scene) {
  63872. return;
  63873. }
  63874. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63875. this._texture = this._getFromCache(this.url, this._noMipmap);
  63876. if (!this._texture) {
  63877. if (this._prefiltered) {
  63878. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63879. }
  63880. else {
  63881. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63882. }
  63883. }
  63884. };
  63885. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63886. return this._textureMatrix;
  63887. };
  63888. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63889. this._textureMatrix = value;
  63890. };
  63891. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63892. var texture = BABYLON.SerializationHelper.Parse(function () {
  63893. var prefiltered = false;
  63894. if (parsedTexture.prefiltered) {
  63895. prefiltered = parsedTexture.prefiltered;
  63896. }
  63897. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63898. }, parsedTexture, scene);
  63899. // Local Cubemaps
  63900. if (parsedTexture.boundingBoxPosition) {
  63901. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63902. }
  63903. if (parsedTexture.boundingBoxSize) {
  63904. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63905. }
  63906. // Animations
  63907. if (parsedTexture.animations) {
  63908. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63909. var parsedAnimation = parsedTexture.animations[animationIndex];
  63910. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63911. }
  63912. }
  63913. return texture;
  63914. };
  63915. CubeTexture.prototype.clone = function () {
  63916. var _this = this;
  63917. return BABYLON.SerializationHelper.Clone(function () {
  63918. var scene = _this.getScene();
  63919. if (!scene) {
  63920. return _this;
  63921. }
  63922. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63923. }, this);
  63924. };
  63925. __decorate([
  63926. BABYLON.serialize("rotationY")
  63927. ], CubeTexture.prototype, "_rotationY", void 0);
  63928. return CubeTexture;
  63929. }(BABYLON.BaseTexture));
  63930. BABYLON.CubeTexture = CubeTexture;
  63931. })(BABYLON || (BABYLON = {}));
  63932. //# sourceMappingURL=babylon.cubeTexture.js.map
  63933. var BABYLON;
  63934. (function (BABYLON) {
  63935. var RenderTargetTexture = /** @class */ (function (_super) {
  63936. __extends(RenderTargetTexture, _super);
  63937. /**
  63938. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63939. * or used a shadow, depth texture...
  63940. * @param name The friendly name of the texture
  63941. * @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)
  63942. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63943. * @param generateMipMaps True if mip maps need to be generated after render.
  63944. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63945. * @param type The type of the buffer in the RTT (int, half float, float...)
  63946. * @param isCube True if a cube texture needs to be created
  63947. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63948. * @param generateDepthBuffer True to generate a depth buffer
  63949. * @param generateStencilBuffer True to generate a stencil buffer
  63950. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63951. */
  63952. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63953. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63954. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63955. if (isCube === void 0) { isCube = false; }
  63956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63957. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63958. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63959. if (isMulti === void 0) { isMulti = false; }
  63960. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63961. _this.isCube = isCube;
  63962. /**
  63963. * Use this list to define the list of mesh you want to render.
  63964. */
  63965. _this.renderList = new Array();
  63966. _this.renderParticles = true;
  63967. _this.renderSprites = false;
  63968. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63969. _this.ignoreCameraViewport = false;
  63970. // Events
  63971. /**
  63972. * An event triggered when the texture is unbind.
  63973. */
  63974. _this.onBeforeBindObservable = new BABYLON.Observable();
  63975. /**
  63976. * An event triggered when the texture is unbind.
  63977. */
  63978. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63979. /**
  63980. * An event triggered before rendering the texture
  63981. */
  63982. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63983. /**
  63984. * An event triggered after rendering the texture
  63985. */
  63986. _this.onAfterRenderObservable = new BABYLON.Observable();
  63987. /**
  63988. * An event triggered after the texture clear
  63989. */
  63990. _this.onClearObservable = new BABYLON.Observable();
  63991. _this._currentRefreshId = -1;
  63992. _this._refreshRate = 1;
  63993. _this._samples = 1;
  63994. /**
  63995. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63996. * It must define where the camera used to render the texture is set
  63997. */
  63998. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63999. scene = _this.getScene();
  64000. if (!scene) {
  64001. return _this;
  64002. }
  64003. _this._engine = scene.getEngine();
  64004. _this.name = name;
  64005. _this.isRenderTarget = true;
  64006. _this._initialSizeParameter = size;
  64007. _this._processSizeParameter(size);
  64008. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  64009. });
  64010. _this._generateMipMaps = generateMipMaps ? true : false;
  64011. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  64012. // Rendering groups
  64013. _this._renderingManager = new BABYLON.RenderingManager(scene);
  64014. if (isMulti) {
  64015. return _this;
  64016. }
  64017. _this._renderTargetOptions = {
  64018. generateMipMaps: generateMipMaps,
  64019. type: type,
  64020. samplingMode: samplingMode,
  64021. generateDepthBuffer: generateDepthBuffer,
  64022. generateStencilBuffer: generateStencilBuffer
  64023. };
  64024. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  64025. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64026. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64027. }
  64028. if (isCube) {
  64029. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  64030. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  64031. _this._textureMatrix = BABYLON.Matrix.Identity();
  64032. }
  64033. else {
  64034. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  64035. }
  64036. return _this;
  64037. }
  64038. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  64039. get: function () {
  64040. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  64041. },
  64042. enumerable: true,
  64043. configurable: true
  64044. });
  64045. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  64046. get: function () {
  64047. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  64048. },
  64049. enumerable: true,
  64050. configurable: true
  64051. });
  64052. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  64053. get: function () {
  64054. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  64055. },
  64056. enumerable: true,
  64057. configurable: true
  64058. });
  64059. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  64060. set: function (callback) {
  64061. if (this._onAfterUnbindObserver) {
  64062. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  64063. }
  64064. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  64065. },
  64066. enumerable: true,
  64067. configurable: true
  64068. });
  64069. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  64070. set: function (callback) {
  64071. if (this._onBeforeRenderObserver) {
  64072. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64073. }
  64074. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64075. },
  64076. enumerable: true,
  64077. configurable: true
  64078. });
  64079. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64080. set: function (callback) {
  64081. if (this._onAfterRenderObserver) {
  64082. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64083. }
  64084. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64085. },
  64086. enumerable: true,
  64087. configurable: true
  64088. });
  64089. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64090. set: function (callback) {
  64091. if (this._onClearObserver) {
  64092. this.onClearObservable.remove(this._onClearObserver);
  64093. }
  64094. this._onClearObserver = this.onClearObservable.add(callback);
  64095. },
  64096. enumerable: true,
  64097. configurable: true
  64098. });
  64099. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64100. get: function () {
  64101. return this._renderTargetOptions;
  64102. },
  64103. enumerable: true,
  64104. configurable: true
  64105. });
  64106. RenderTargetTexture.prototype._onRatioRescale = function () {
  64107. if (this._sizeRatio) {
  64108. this.resize(this._initialSizeParameter);
  64109. }
  64110. };
  64111. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64112. get: function () {
  64113. return this._boundingBoxSize;
  64114. },
  64115. /**
  64116. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64117. * When defined, the cubemap will switch to local mode
  64118. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64119. * @example https://www.babylonjs-playground.com/#RNASML
  64120. */
  64121. set: function (value) {
  64122. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64123. return;
  64124. }
  64125. this._boundingBoxSize = value;
  64126. var scene = this.getScene();
  64127. if (scene) {
  64128. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64129. }
  64130. },
  64131. enumerable: true,
  64132. configurable: true
  64133. });
  64134. /**
  64135. * Creates a depth stencil texture.
  64136. * This is only available in WebGL 2 or with the depth texture extension available.
  64137. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64138. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64139. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64140. */
  64141. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64142. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64143. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64144. if (generateStencil === void 0) { generateStencil = false; }
  64145. if (!this.getScene()) {
  64146. return;
  64147. }
  64148. var engine = this.getScene().getEngine();
  64149. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64150. bilinearFiltering: bilinearFiltering,
  64151. comparisonFunction: comparisonFunction,
  64152. generateStencil: generateStencil,
  64153. isCube: this.isCube
  64154. });
  64155. engine.setFrameBufferDepthStencilTexture(this);
  64156. };
  64157. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64158. if (size.ratio) {
  64159. this._sizeRatio = size.ratio;
  64160. this._size = {
  64161. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64162. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64163. };
  64164. }
  64165. else {
  64166. this._size = size;
  64167. }
  64168. };
  64169. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64170. get: function () {
  64171. return this._samples;
  64172. },
  64173. set: function (value) {
  64174. if (this._samples === value) {
  64175. return;
  64176. }
  64177. var scene = this.getScene();
  64178. if (!scene) {
  64179. return;
  64180. }
  64181. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64182. },
  64183. enumerable: true,
  64184. configurable: true
  64185. });
  64186. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64187. this._currentRefreshId = -1;
  64188. };
  64189. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64190. get: function () {
  64191. return this._refreshRate;
  64192. },
  64193. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64194. set: function (value) {
  64195. this._refreshRate = value;
  64196. this.resetRefreshCounter();
  64197. },
  64198. enumerable: true,
  64199. configurable: true
  64200. });
  64201. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64202. if (!this._postProcessManager) {
  64203. var scene = this.getScene();
  64204. if (!scene) {
  64205. return;
  64206. }
  64207. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64208. this._postProcesses = new Array();
  64209. }
  64210. this._postProcesses.push(postProcess);
  64211. this._postProcesses[0].autoClear = false;
  64212. };
  64213. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64214. if (!this._postProcesses) {
  64215. return;
  64216. }
  64217. if (dispose) {
  64218. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64219. var postProcess = _a[_i];
  64220. postProcess.dispose();
  64221. }
  64222. }
  64223. this._postProcesses = [];
  64224. };
  64225. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64226. if (!this._postProcesses) {
  64227. return;
  64228. }
  64229. var index = this._postProcesses.indexOf(postProcess);
  64230. if (index === -1) {
  64231. return;
  64232. }
  64233. this._postProcesses.splice(index, 1);
  64234. if (this._postProcesses.length > 0) {
  64235. this._postProcesses[0].autoClear = false;
  64236. }
  64237. };
  64238. RenderTargetTexture.prototype._shouldRender = function () {
  64239. if (this._currentRefreshId === -1) { // At least render once
  64240. this._currentRefreshId = 1;
  64241. return true;
  64242. }
  64243. if (this.refreshRate === this._currentRefreshId) {
  64244. this._currentRefreshId = 1;
  64245. return true;
  64246. }
  64247. this._currentRefreshId++;
  64248. return false;
  64249. };
  64250. RenderTargetTexture.prototype.getRenderSize = function () {
  64251. if (this._size.width) {
  64252. return this._size.width;
  64253. }
  64254. return this._size;
  64255. };
  64256. RenderTargetTexture.prototype.getRenderWidth = function () {
  64257. if (this._size.width) {
  64258. return this._size.width;
  64259. }
  64260. return this._size;
  64261. };
  64262. RenderTargetTexture.prototype.getRenderHeight = function () {
  64263. if (this._size.width) {
  64264. return this._size.height;
  64265. }
  64266. return this._size;
  64267. };
  64268. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64269. get: function () {
  64270. return true;
  64271. },
  64272. enumerable: true,
  64273. configurable: true
  64274. });
  64275. RenderTargetTexture.prototype.scale = function (ratio) {
  64276. var newSize = this.getRenderSize() * ratio;
  64277. this.resize(newSize);
  64278. };
  64279. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64280. if (this.isCube) {
  64281. return this._textureMatrix;
  64282. }
  64283. return _super.prototype.getReflectionTextureMatrix.call(this);
  64284. };
  64285. RenderTargetTexture.prototype.resize = function (size) {
  64286. this.releaseInternalTexture();
  64287. var scene = this.getScene();
  64288. if (!scene) {
  64289. return;
  64290. }
  64291. this._processSizeParameter(size);
  64292. if (this.isCube) {
  64293. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64294. }
  64295. else {
  64296. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64297. }
  64298. };
  64299. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64300. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64301. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64302. var scene = this.getScene();
  64303. if (!scene) {
  64304. return;
  64305. }
  64306. var engine = scene.getEngine();
  64307. if (this.useCameraPostProcesses !== undefined) {
  64308. useCameraPostProcess = this.useCameraPostProcesses;
  64309. }
  64310. if (this._waitingRenderList) {
  64311. this.renderList = [];
  64312. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64313. var id = this._waitingRenderList[index];
  64314. var mesh_1 = scene.getMeshByID(id);
  64315. if (mesh_1) {
  64316. this.renderList.push(mesh_1);
  64317. }
  64318. }
  64319. delete this._waitingRenderList;
  64320. }
  64321. // Is predicate defined?
  64322. if (this.renderListPredicate) {
  64323. if (this.renderList) {
  64324. this.renderList.splice(0); // Clear previous renderList
  64325. }
  64326. else {
  64327. this.renderList = [];
  64328. }
  64329. var scene = this.getScene();
  64330. if (!scene) {
  64331. return;
  64332. }
  64333. var sceneMeshes = scene.meshes;
  64334. for (var index = 0; index < sceneMeshes.length; index++) {
  64335. var mesh = sceneMeshes[index];
  64336. if (this.renderListPredicate(mesh)) {
  64337. this.renderList.push(mesh);
  64338. }
  64339. }
  64340. }
  64341. this.onBeforeBindObservable.notifyObservers(this);
  64342. // Set custom projection.
  64343. // Needs to be before binding to prevent changing the aspect ratio.
  64344. var camera;
  64345. if (this.activeCamera) {
  64346. camera = this.activeCamera;
  64347. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64348. if (this.activeCamera !== scene.activeCamera) {
  64349. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64350. }
  64351. }
  64352. else {
  64353. camera = scene.activeCamera;
  64354. if (camera) {
  64355. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64356. }
  64357. }
  64358. // Prepare renderingManager
  64359. this._renderingManager.reset();
  64360. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64361. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64362. var sceneRenderId = scene.getRenderId();
  64363. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64364. var mesh = currentRenderList[meshIndex];
  64365. if (mesh) {
  64366. if (!mesh.isReady(this.refreshRate === 0)) {
  64367. this.resetRefreshCounter();
  64368. continue;
  64369. }
  64370. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64371. var isMasked = void 0;
  64372. if (!this.renderList && camera) {
  64373. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64374. }
  64375. else {
  64376. isMasked = false;
  64377. }
  64378. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64379. mesh._activate(sceneRenderId);
  64380. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64381. var subMesh = mesh.subMeshes[subIndex];
  64382. scene._activeIndices.addCount(subMesh.indexCount, false);
  64383. this._renderingManager.dispatch(subMesh, mesh);
  64384. }
  64385. }
  64386. }
  64387. }
  64388. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64389. var particleSystem = scene.particleSystems[particleIndex];
  64390. var emitter = particleSystem.emitter;
  64391. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64392. continue;
  64393. }
  64394. if (currentRenderList.indexOf(emitter) >= 0) {
  64395. this._renderingManager.dispatchParticles(particleSystem);
  64396. }
  64397. }
  64398. if (this.isCube) {
  64399. for (var face = 0; face < 6; face++) {
  64400. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64401. scene.incrementRenderId();
  64402. scene.resetCachedMaterial();
  64403. }
  64404. }
  64405. else {
  64406. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64407. }
  64408. this.onAfterUnbindObservable.notifyObservers(this);
  64409. if (scene.activeCamera) {
  64410. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64411. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64412. }
  64413. engine.setViewport(scene.activeCamera.viewport);
  64414. }
  64415. scene.resetCachedMaterial();
  64416. };
  64417. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64418. var minimum = 128;
  64419. var x = renderDimension * scale;
  64420. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64421. // Ensure we don't exceed the render dimension (while staying POT)
  64422. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64423. };
  64424. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64425. var _this = this;
  64426. if (!this._texture) {
  64427. return;
  64428. }
  64429. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64430. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64431. });
  64432. };
  64433. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64434. var scene = this.getScene();
  64435. if (!scene) {
  64436. return;
  64437. }
  64438. var engine = scene.getEngine();
  64439. if (!this._texture) {
  64440. return;
  64441. }
  64442. // Bind
  64443. if (this._postProcessManager) {
  64444. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64445. }
  64446. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64447. if (this._texture) {
  64448. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64449. }
  64450. }
  64451. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64452. // Clear
  64453. if (this.onClearObservable.hasObservers()) {
  64454. this.onClearObservable.notifyObservers(engine);
  64455. }
  64456. else {
  64457. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64458. }
  64459. if (!this._doNotChangeAspectRatio) {
  64460. scene.updateTransformMatrix(true);
  64461. }
  64462. // Render
  64463. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64464. if (this._postProcessManager) {
  64465. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64466. }
  64467. else if (useCameraPostProcess) {
  64468. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64469. }
  64470. if (!this._doNotChangeAspectRatio) {
  64471. scene.updateTransformMatrix(true);
  64472. }
  64473. // Dump ?
  64474. if (dumpForDebug) {
  64475. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64476. }
  64477. // Unbind
  64478. if (!this.isCube || faceIndex === 5) {
  64479. if (this.isCube) {
  64480. if (faceIndex === 5) {
  64481. engine.generateMipMapsForCubemap(this._texture);
  64482. }
  64483. }
  64484. this.unbindFrameBuffer(engine, faceIndex);
  64485. }
  64486. else {
  64487. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64488. }
  64489. };
  64490. /**
  64491. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64492. * This allowed control for front to back rendering or reversly depending of the special needs.
  64493. *
  64494. * @param renderingGroupId The rendering group id corresponding to its index
  64495. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64496. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64497. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64498. */
  64499. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64500. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64501. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64502. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64503. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64504. };
  64505. /**
  64506. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64507. *
  64508. * @param renderingGroupId The rendering group id corresponding to its index
  64509. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64510. */
  64511. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64512. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64513. };
  64514. RenderTargetTexture.prototype.clone = function () {
  64515. var textureSize = this.getSize();
  64516. 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);
  64517. // Base texture
  64518. newTexture.hasAlpha = this.hasAlpha;
  64519. newTexture.level = this.level;
  64520. // RenderTarget Texture
  64521. newTexture.coordinatesMode = this.coordinatesMode;
  64522. if (this.renderList) {
  64523. newTexture.renderList = this.renderList.slice(0);
  64524. }
  64525. return newTexture;
  64526. };
  64527. RenderTargetTexture.prototype.serialize = function () {
  64528. if (!this.name) {
  64529. return null;
  64530. }
  64531. var serializationObject = _super.prototype.serialize.call(this);
  64532. serializationObject.renderTargetSize = this.getRenderSize();
  64533. serializationObject.renderList = [];
  64534. if (this.renderList) {
  64535. for (var index = 0; index < this.renderList.length; index++) {
  64536. serializationObject.renderList.push(this.renderList[index].id);
  64537. }
  64538. }
  64539. return serializationObject;
  64540. };
  64541. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64542. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64543. var objBuffer = this.getInternalTexture();
  64544. var scene = this.getScene();
  64545. if (objBuffer && scene) {
  64546. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64547. }
  64548. };
  64549. RenderTargetTexture.prototype.dispose = function () {
  64550. if (this._postProcessManager) {
  64551. this._postProcessManager.dispose();
  64552. this._postProcessManager = null;
  64553. }
  64554. this.clearPostProcesses(true);
  64555. if (this._resizeObserver) {
  64556. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64557. this._resizeObserver = null;
  64558. }
  64559. this.renderList = null;
  64560. // Remove from custom render targets
  64561. var scene = this.getScene();
  64562. if (!scene) {
  64563. return;
  64564. }
  64565. var index = scene.customRenderTargets.indexOf(this);
  64566. if (index >= 0) {
  64567. scene.customRenderTargets.splice(index, 1);
  64568. }
  64569. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64570. var camera = _a[_i];
  64571. index = camera.customRenderTargets.indexOf(this);
  64572. if (index >= 0) {
  64573. camera.customRenderTargets.splice(index, 1);
  64574. }
  64575. }
  64576. _super.prototype.dispose.call(this);
  64577. };
  64578. RenderTargetTexture.prototype._rebuild = function () {
  64579. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64580. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64581. }
  64582. if (this._postProcessManager) {
  64583. this._postProcessManager._rebuild();
  64584. }
  64585. };
  64586. /**
  64587. * Clear the info related to rendering groups preventing retention point in material dispose.
  64588. */
  64589. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64590. if (this._renderingManager) {
  64591. this._renderingManager.freeRenderingGroups();
  64592. }
  64593. };
  64594. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64595. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64596. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64597. return RenderTargetTexture;
  64598. }(BABYLON.Texture));
  64599. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64600. })(BABYLON || (BABYLON = {}));
  64601. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64602. var BABYLON;
  64603. (function (BABYLON) {
  64604. ;
  64605. var MultiRenderTarget = /** @class */ (function (_super) {
  64606. __extends(MultiRenderTarget, _super);
  64607. function MultiRenderTarget(name, size, count, scene, options) {
  64608. var _this = this;
  64609. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64610. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64611. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64612. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64613. _this._engine = scene.getEngine();
  64614. if (!_this.isSupported) {
  64615. _this.dispose();
  64616. return;
  64617. }
  64618. var types = [];
  64619. var samplingModes = [];
  64620. for (var i = 0; i < count; i++) {
  64621. if (options && options.types && options.types[i] !== undefined) {
  64622. types.push(options.types[i]);
  64623. }
  64624. else {
  64625. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64626. }
  64627. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64628. samplingModes.push(options.samplingModes[i]);
  64629. }
  64630. else {
  64631. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64632. }
  64633. }
  64634. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64635. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64636. _this._size = size;
  64637. _this._multiRenderTargetOptions = {
  64638. samplingModes: samplingModes,
  64639. generateMipMaps: generateMipMaps,
  64640. generateDepthBuffer: generateDepthBuffer,
  64641. generateStencilBuffer: generateStencilBuffer,
  64642. generateDepthTexture: generateDepthTexture,
  64643. types: types,
  64644. textureCount: count
  64645. };
  64646. _this._createInternalTextures();
  64647. _this._createTextures();
  64648. return _this;
  64649. }
  64650. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64651. get: function () {
  64652. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64653. },
  64654. enumerable: true,
  64655. configurable: true
  64656. });
  64657. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64658. get: function () {
  64659. return this._textures;
  64660. },
  64661. enumerable: true,
  64662. configurable: true
  64663. });
  64664. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64665. get: function () {
  64666. return this._textures[this._textures.length - 1];
  64667. },
  64668. enumerable: true,
  64669. configurable: true
  64670. });
  64671. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64672. set: function (wrap) {
  64673. if (this._textures) {
  64674. for (var i = 0; i < this._textures.length; i++) {
  64675. this._textures[i].wrapU = wrap;
  64676. }
  64677. }
  64678. },
  64679. enumerable: true,
  64680. configurable: true
  64681. });
  64682. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64683. set: function (wrap) {
  64684. if (this._textures) {
  64685. for (var i = 0; i < this._textures.length; i++) {
  64686. this._textures[i].wrapV = wrap;
  64687. }
  64688. }
  64689. },
  64690. enumerable: true,
  64691. configurable: true
  64692. });
  64693. MultiRenderTarget.prototype._rebuild = function () {
  64694. this.releaseInternalTextures();
  64695. this._createInternalTextures();
  64696. for (var i = 0; i < this._internalTextures.length; i++) {
  64697. var texture = this._textures[i];
  64698. texture._texture = this._internalTextures[i];
  64699. }
  64700. // Keeps references to frame buffer and stencil/depth buffer
  64701. this._texture = this._internalTextures[0];
  64702. };
  64703. MultiRenderTarget.prototype._createInternalTextures = function () {
  64704. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64705. };
  64706. MultiRenderTarget.prototype._createTextures = function () {
  64707. this._textures = [];
  64708. for (var i = 0; i < this._internalTextures.length; i++) {
  64709. var texture = new BABYLON.Texture(null, this.getScene());
  64710. texture._texture = this._internalTextures[i];
  64711. this._textures.push(texture);
  64712. }
  64713. // Keeps references to frame buffer and stencil/depth buffer
  64714. this._texture = this._internalTextures[0];
  64715. };
  64716. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64717. get: function () {
  64718. return this._samples;
  64719. },
  64720. set: function (value) {
  64721. if (this._samples === value) {
  64722. return;
  64723. }
  64724. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64725. },
  64726. enumerable: true,
  64727. configurable: true
  64728. });
  64729. MultiRenderTarget.prototype.resize = function (size) {
  64730. this.releaseInternalTextures();
  64731. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64732. this._createInternalTextures();
  64733. };
  64734. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64735. var _this = this;
  64736. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64737. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64738. });
  64739. };
  64740. MultiRenderTarget.prototype.dispose = function () {
  64741. this.releaseInternalTextures();
  64742. _super.prototype.dispose.call(this);
  64743. };
  64744. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64745. if (!this._internalTextures) {
  64746. return;
  64747. }
  64748. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64749. if (this._internalTextures[i] !== undefined) {
  64750. this._internalTextures[i].dispose();
  64751. this._internalTextures.splice(i, 1);
  64752. }
  64753. }
  64754. };
  64755. return MultiRenderTarget;
  64756. }(BABYLON.RenderTargetTexture));
  64757. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64758. })(BABYLON || (BABYLON = {}));
  64759. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64760. var BABYLON;
  64761. (function (BABYLON) {
  64762. var MirrorTexture = /** @class */ (function (_super) {
  64763. __extends(MirrorTexture, _super);
  64764. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64765. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64766. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64767. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64768. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64769. _this.scene = scene;
  64770. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64771. _this._transformMatrix = BABYLON.Matrix.Zero();
  64772. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64773. _this._adaptiveBlurKernel = 0;
  64774. _this._blurKernelX = 0;
  64775. _this._blurKernelY = 0;
  64776. _this._blurRatio = 1.0;
  64777. _this.ignoreCameraViewport = true;
  64778. _this._updateGammaSpace();
  64779. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64780. _this._updateGammaSpace;
  64781. });
  64782. _this.onBeforeRenderObservable.add(function () {
  64783. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64784. _this._savedViewMatrix = scene.getViewMatrix();
  64785. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64786. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64787. scene.clipPlane = _this.mirrorPlane;
  64788. scene.getEngine().cullBackFaces = false;
  64789. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64790. });
  64791. _this.onAfterRenderObservable.add(function () {
  64792. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64793. scene.getEngine().cullBackFaces = true;
  64794. scene._mirroredCameraPosition = null;
  64795. delete scene.clipPlane;
  64796. });
  64797. return _this;
  64798. }
  64799. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64800. get: function () {
  64801. return this._blurRatio;
  64802. },
  64803. set: function (value) {
  64804. if (this._blurRatio === value) {
  64805. return;
  64806. }
  64807. this._blurRatio = value;
  64808. this._preparePostProcesses();
  64809. },
  64810. enumerable: true,
  64811. configurable: true
  64812. });
  64813. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64814. set: function (value) {
  64815. this._adaptiveBlurKernel = value;
  64816. this._autoComputeBlurKernel();
  64817. },
  64818. enumerable: true,
  64819. configurable: true
  64820. });
  64821. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64822. set: function (value) {
  64823. this.blurKernelX = value;
  64824. this.blurKernelY = value;
  64825. },
  64826. enumerable: true,
  64827. configurable: true
  64828. });
  64829. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64830. get: function () {
  64831. return this._blurKernelX;
  64832. },
  64833. set: function (value) {
  64834. if (this._blurKernelX === value) {
  64835. return;
  64836. }
  64837. this._blurKernelX = value;
  64838. this._preparePostProcesses();
  64839. },
  64840. enumerable: true,
  64841. configurable: true
  64842. });
  64843. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64844. get: function () {
  64845. return this._blurKernelY;
  64846. },
  64847. set: function (value) {
  64848. if (this._blurKernelY === value) {
  64849. return;
  64850. }
  64851. this._blurKernelY = value;
  64852. this._preparePostProcesses();
  64853. },
  64854. enumerable: true,
  64855. configurable: true
  64856. });
  64857. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64858. var engine = this.getScene().getEngine();
  64859. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64860. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64861. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64862. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64863. };
  64864. MirrorTexture.prototype._onRatioRescale = function () {
  64865. if (this._sizeRatio) {
  64866. this.resize(this._initialSizeParameter);
  64867. if (!this._adaptiveBlurKernel) {
  64868. this._preparePostProcesses();
  64869. }
  64870. }
  64871. if (this._adaptiveBlurKernel) {
  64872. this._autoComputeBlurKernel();
  64873. }
  64874. };
  64875. MirrorTexture.prototype._updateGammaSpace = function () {
  64876. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64877. };
  64878. MirrorTexture.prototype._preparePostProcesses = function () {
  64879. this.clearPostProcesses(true);
  64880. if (this._blurKernelX && this._blurKernelY) {
  64881. var engine = this.getScene().getEngine();
  64882. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64883. 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);
  64884. this._blurX.autoClear = false;
  64885. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64886. this._blurX.inputTexture = this._texture;
  64887. }
  64888. else {
  64889. this._blurX.alwaysForcePOT = true;
  64890. }
  64891. 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);
  64892. this._blurY.autoClear = false;
  64893. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64894. this.addPostProcess(this._blurX);
  64895. this.addPostProcess(this._blurY);
  64896. }
  64897. else {
  64898. if (this._blurY) {
  64899. this.removePostProcess(this._blurY);
  64900. this._blurY.dispose();
  64901. this._blurY = null;
  64902. }
  64903. if (this._blurX) {
  64904. this.removePostProcess(this._blurX);
  64905. this._blurX.dispose();
  64906. this._blurX = null;
  64907. }
  64908. }
  64909. };
  64910. MirrorTexture.prototype.clone = function () {
  64911. var scene = this.getScene();
  64912. if (!scene) {
  64913. return this;
  64914. }
  64915. var textureSize = this.getSize();
  64916. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64917. // Base texture
  64918. newTexture.hasAlpha = this.hasAlpha;
  64919. newTexture.level = this.level;
  64920. // Mirror Texture
  64921. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64922. if (this.renderList) {
  64923. newTexture.renderList = this.renderList.slice(0);
  64924. }
  64925. return newTexture;
  64926. };
  64927. MirrorTexture.prototype.serialize = function () {
  64928. if (!this.name) {
  64929. return null;
  64930. }
  64931. var serializationObject = _super.prototype.serialize.call(this);
  64932. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64933. return serializationObject;
  64934. };
  64935. MirrorTexture.prototype.dispose = function () {
  64936. _super.prototype.dispose.call(this);
  64937. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64938. };
  64939. return MirrorTexture;
  64940. }(BABYLON.RenderTargetTexture));
  64941. BABYLON.MirrorTexture = MirrorTexture;
  64942. })(BABYLON || (BABYLON = {}));
  64943. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64944. var BABYLON;
  64945. (function (BABYLON) {
  64946. /**
  64947. * Creates a refraction texture used by refraction channel of the standard material.
  64948. * @param name the texture name
  64949. * @param size size of the underlying texture
  64950. * @param scene root scene
  64951. */
  64952. var RefractionTexture = /** @class */ (function (_super) {
  64953. __extends(RefractionTexture, _super);
  64954. function RefractionTexture(name, size, scene, generateMipMaps) {
  64955. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64956. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64957. _this.depth = 2.0;
  64958. _this.onBeforeRenderObservable.add(function () {
  64959. scene.clipPlane = _this.refractionPlane;
  64960. });
  64961. _this.onAfterRenderObservable.add(function () {
  64962. delete scene.clipPlane;
  64963. });
  64964. return _this;
  64965. }
  64966. RefractionTexture.prototype.clone = function () {
  64967. var scene = this.getScene();
  64968. if (!scene) {
  64969. return this;
  64970. }
  64971. var textureSize = this.getSize();
  64972. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64973. // Base texture
  64974. newTexture.hasAlpha = this.hasAlpha;
  64975. newTexture.level = this.level;
  64976. // Refraction Texture
  64977. newTexture.refractionPlane = this.refractionPlane.clone();
  64978. if (this.renderList) {
  64979. newTexture.renderList = this.renderList.slice(0);
  64980. }
  64981. newTexture.depth = this.depth;
  64982. return newTexture;
  64983. };
  64984. RefractionTexture.prototype.serialize = function () {
  64985. if (!this.name) {
  64986. return null;
  64987. }
  64988. var serializationObject = _super.prototype.serialize.call(this);
  64989. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64990. serializationObject.depth = this.depth;
  64991. return serializationObject;
  64992. };
  64993. return RefractionTexture;
  64994. }(BABYLON.RenderTargetTexture));
  64995. BABYLON.RefractionTexture = RefractionTexture;
  64996. })(BABYLON || (BABYLON = {}));
  64997. //# sourceMappingURL=babylon.refractionTexture.js.map
  64998. var BABYLON;
  64999. (function (BABYLON) {
  65000. /**
  65001. * A class extending {BABYLON.Texture} allowing drawing on a texture
  65002. * @see http://doc.babylonjs.com/how_to/dynamictexture
  65003. */
  65004. var DynamicTexture = /** @class */ (function (_super) {
  65005. __extends(DynamicTexture, _super);
  65006. /**
  65007. * Creates a {BABYLON.DynamicTexture}
  65008. * @param name defines the name of the texture
  65009. * @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
  65010. * @param scene defines the scene where you want the texture
  65011. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  65012. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  65013. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  65014. */
  65015. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  65016. if (scene === void 0) { scene = null; }
  65017. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65018. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65019. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  65020. _this.name = name;
  65021. _this._engine = _this.getScene().getEngine();
  65022. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65023. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65024. _this._generateMipMaps = generateMipMaps;
  65025. if (options.getContext) {
  65026. _this._canvas = options;
  65027. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65028. }
  65029. else {
  65030. _this._canvas = document.createElement("canvas");
  65031. if (options.width || options.width === 0) {
  65032. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65033. }
  65034. else {
  65035. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  65036. }
  65037. }
  65038. var textureSize = _this.getSize();
  65039. _this._canvas.width = textureSize.width;
  65040. _this._canvas.height = textureSize.height;
  65041. _this._context = _this._canvas.getContext("2d");
  65042. return _this;
  65043. }
  65044. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  65045. /**
  65046. * Gets the current state of canRescale
  65047. */
  65048. get: function () {
  65049. return true;
  65050. },
  65051. enumerable: true,
  65052. configurable: true
  65053. });
  65054. DynamicTexture.prototype._recreate = function (textureSize) {
  65055. this._canvas.width = textureSize.width;
  65056. this._canvas.height = textureSize.height;
  65057. this.releaseInternalTexture();
  65058. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  65059. };
  65060. /**
  65061. * Scales the texture
  65062. * @param ratio the scale factor to apply to both width and height
  65063. */
  65064. DynamicTexture.prototype.scale = function (ratio) {
  65065. var textureSize = this.getSize();
  65066. textureSize.width *= ratio;
  65067. textureSize.height *= ratio;
  65068. this._recreate(textureSize);
  65069. };
  65070. /**
  65071. * Resizes the texture
  65072. * @param width the new width
  65073. * @param height the new height
  65074. */
  65075. DynamicTexture.prototype.scaleTo = function (width, height) {
  65076. var textureSize = this.getSize();
  65077. textureSize.width = width;
  65078. textureSize.height = height;
  65079. this._recreate(textureSize);
  65080. };
  65081. /**
  65082. * Gets the context of the canvas used by the texture
  65083. * @returns the canvas context of the dynamic texture
  65084. */
  65085. DynamicTexture.prototype.getContext = function () {
  65086. return this._context;
  65087. };
  65088. /**
  65089. * Clears the texture
  65090. */
  65091. DynamicTexture.prototype.clear = function () {
  65092. var size = this.getSize();
  65093. this._context.fillRect(0, 0, size.width, size.height);
  65094. };
  65095. /**
  65096. * Updates the texture
  65097. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65098. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65099. */
  65100. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65101. if (premulAlpha === void 0) { premulAlpha = false; }
  65102. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65103. };
  65104. /**
  65105. * Draws text onto the texture
  65106. * @param text defines the text to be drawn
  65107. * @param x defines the placement of the text from the left
  65108. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65109. * @param font defines the font to be used with font-style, font-size, font-name
  65110. * @param color defines the color used for the text
  65111. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65112. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65113. * @param update defines whether texture is immediately update (default is true)
  65114. */
  65115. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65116. if (update === void 0) { update = true; }
  65117. var size = this.getSize();
  65118. if (clearColor) {
  65119. this._context.fillStyle = clearColor;
  65120. this._context.fillRect(0, 0, size.width, size.height);
  65121. }
  65122. this._context.font = font;
  65123. if (x === null || x === undefined) {
  65124. var textSize = this._context.measureText(text);
  65125. x = (size.width - textSize.width) / 2;
  65126. }
  65127. if (y === null || y === undefined) {
  65128. var fontSize = parseInt((font.replace(/\D/g, '')));
  65129. y = (size.height / 2) + (fontSize / 3.65);
  65130. }
  65131. this._context.fillStyle = color;
  65132. this._context.fillText(text, x, y);
  65133. if (update) {
  65134. this.update(invertY);
  65135. }
  65136. };
  65137. /**
  65138. * Clones the texture
  65139. * @returns the clone of the texture.
  65140. */
  65141. DynamicTexture.prototype.clone = function () {
  65142. var scene = this.getScene();
  65143. if (!scene) {
  65144. return this;
  65145. }
  65146. var textureSize = this.getSize();
  65147. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65148. // Base texture
  65149. newTexture.hasAlpha = this.hasAlpha;
  65150. newTexture.level = this.level;
  65151. // Dynamic Texture
  65152. newTexture.wrapU = this.wrapU;
  65153. newTexture.wrapV = this.wrapV;
  65154. return newTexture;
  65155. };
  65156. /** @hidden */
  65157. DynamicTexture.prototype._rebuild = function () {
  65158. this.update();
  65159. };
  65160. return DynamicTexture;
  65161. }(BABYLON.Texture));
  65162. BABYLON.DynamicTexture = DynamicTexture;
  65163. })(BABYLON || (BABYLON = {}));
  65164. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65165. var BABYLON;
  65166. (function (BABYLON) {
  65167. var VideoTexture = /** @class */ (function (_super) {
  65168. __extends(VideoTexture, _super);
  65169. /**
  65170. * Creates a video texture.
  65171. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65172. * @param {string | null} name optional name, will detect from video source, if not defined
  65173. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65174. * @param {BABYLON.Scene} scene is obviously the current scene.
  65175. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65176. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65177. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65178. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65179. */
  65180. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65181. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65182. if (invertY === void 0) { invertY = false; }
  65183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65184. if (settings === void 0) { settings = {
  65185. autoPlay: true,
  65186. loop: true,
  65187. autoUpdateTexture: true,
  65188. }; }
  65189. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65190. _this._stillImageCaptured = false;
  65191. _this._createInternalTexture = function () {
  65192. if (_this._texture != null) {
  65193. return;
  65194. }
  65195. if (!_this._engine.needPOTTextures ||
  65196. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65197. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65198. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65199. }
  65200. else {
  65201. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65202. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65203. _this._generateMipMaps = false;
  65204. }
  65205. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65206. if (!_this.video.autoplay) {
  65207. var oldHandler_1 = _this.video.onplaying;
  65208. _this.video.onplaying = function () {
  65209. _this.video.onplaying = oldHandler_1;
  65210. _this._texture.isReady = true;
  65211. _this._updateInternalTexture();
  65212. _this.video.pause();
  65213. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65214. _this.onLoadObservable.notifyObservers(_this);
  65215. }
  65216. };
  65217. _this.video.play();
  65218. }
  65219. else {
  65220. _this._texture.isReady = true;
  65221. _this._updateInternalTexture();
  65222. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65223. _this.onLoadObservable.notifyObservers(_this);
  65224. }
  65225. }
  65226. };
  65227. _this.reset = function () {
  65228. if (_this._texture == null) {
  65229. return;
  65230. }
  65231. _this._texture.dispose();
  65232. _this._texture = null;
  65233. };
  65234. _this._updateInternalTexture = function (e) {
  65235. if (_this._texture == null || !_this._texture.isReady) {
  65236. return;
  65237. }
  65238. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65239. return;
  65240. }
  65241. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65242. };
  65243. _this._engine = _this.getScene().getEngine();
  65244. _this._generateMipMaps = generateMipMaps;
  65245. _this._samplingMode = samplingMode;
  65246. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65247. _this.name = name || _this._getName(src);
  65248. _this.video = _this._getVideo(src);
  65249. if (settings.autoPlay !== undefined) {
  65250. _this.video.autoplay = settings.autoPlay;
  65251. }
  65252. if (settings.loop !== undefined) {
  65253. _this.video.loop = settings.loop;
  65254. }
  65255. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65256. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65257. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65258. _this.video.addEventListener("emptied", _this.reset);
  65259. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65260. _this._createInternalTexture();
  65261. }
  65262. return _this;
  65263. }
  65264. VideoTexture.prototype._getName = function (src) {
  65265. if (src instanceof HTMLVideoElement) {
  65266. return src.currentSrc;
  65267. }
  65268. if (typeof src === "object") {
  65269. return src.toString();
  65270. }
  65271. return src;
  65272. };
  65273. ;
  65274. VideoTexture.prototype._getVideo = function (src) {
  65275. if (src instanceof HTMLVideoElement) {
  65276. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65277. return src;
  65278. }
  65279. var video = document.createElement("video");
  65280. if (typeof src === "string") {
  65281. BABYLON.Tools.SetCorsBehavior(src, video);
  65282. video.src = src;
  65283. }
  65284. else {
  65285. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65286. src.forEach(function (url) {
  65287. var source = document.createElement("source");
  65288. source.src = url;
  65289. video.appendChild(source);
  65290. });
  65291. }
  65292. return video;
  65293. };
  65294. ;
  65295. /**
  65296. * Internal method to initiate `update`.
  65297. */
  65298. VideoTexture.prototype._rebuild = function () {
  65299. this.update();
  65300. };
  65301. /**
  65302. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65303. */
  65304. VideoTexture.prototype.update = function () {
  65305. if (!this.autoUpdateTexture) {
  65306. // Expecting user to call `updateTexture` manually
  65307. return;
  65308. }
  65309. this.updateTexture(true);
  65310. };
  65311. /**
  65312. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65313. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65314. */
  65315. VideoTexture.prototype.updateTexture = function (isVisible) {
  65316. if (!isVisible) {
  65317. return;
  65318. }
  65319. if (this.video.paused && this._stillImageCaptured) {
  65320. return;
  65321. }
  65322. this._stillImageCaptured = true;
  65323. this._updateInternalTexture();
  65324. };
  65325. /**
  65326. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65327. * @param url New url.
  65328. */
  65329. VideoTexture.prototype.updateURL = function (url) {
  65330. this.video.src = url;
  65331. };
  65332. VideoTexture.prototype.dispose = function () {
  65333. _super.prototype.dispose.call(this);
  65334. this.video.removeEventListener("canplay", this._createInternalTexture);
  65335. this.video.removeEventListener("paused", this._updateInternalTexture);
  65336. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65337. this.video.removeEventListener("emptied", this.reset);
  65338. this.video.pause();
  65339. };
  65340. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65341. var video = document.createElement("video");
  65342. var constraintsDeviceId;
  65343. if (constraints && constraints.deviceId) {
  65344. constraintsDeviceId = {
  65345. exact: constraints.deviceId,
  65346. };
  65347. }
  65348. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65349. if (navigator.mediaDevices) {
  65350. navigator.mediaDevices.getUserMedia({ video: constraints })
  65351. .then(function (stream) {
  65352. if (video.mozSrcObject !== undefined) {
  65353. // hack for Firefox < 19
  65354. video.mozSrcObject = stream;
  65355. }
  65356. else {
  65357. video.srcObject = stream;
  65358. }
  65359. var onPlaying = function () {
  65360. if (onReady) {
  65361. onReady(new VideoTexture("video", video, scene, true, true));
  65362. }
  65363. video.removeEventListener("playing", onPlaying);
  65364. };
  65365. video.addEventListener("playing", onPlaying);
  65366. video.play();
  65367. })
  65368. .catch(function (err) {
  65369. BABYLON.Tools.Error(err.name);
  65370. });
  65371. }
  65372. else {
  65373. navigator.getUserMedia =
  65374. navigator.getUserMedia ||
  65375. navigator.webkitGetUserMedia ||
  65376. navigator.mozGetUserMedia ||
  65377. navigator.msGetUserMedia;
  65378. if (navigator.getUserMedia) {
  65379. navigator.getUserMedia({
  65380. video: {
  65381. deviceId: constraintsDeviceId,
  65382. width: {
  65383. min: (constraints && constraints.minWidth) || 256,
  65384. max: (constraints && constraints.maxWidth) || 640,
  65385. },
  65386. height: {
  65387. min: (constraints && constraints.minHeight) || 256,
  65388. max: (constraints && constraints.maxHeight) || 480,
  65389. },
  65390. },
  65391. }, function (stream) {
  65392. if (video.mozSrcObject !== undefined) {
  65393. // hack for Firefox < 19
  65394. video.mozSrcObject = stream;
  65395. }
  65396. else {
  65397. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65398. }
  65399. video.play();
  65400. if (onReady) {
  65401. onReady(new VideoTexture("video", video, scene, true, true));
  65402. }
  65403. }, function (e) {
  65404. BABYLON.Tools.Error(e.name);
  65405. });
  65406. }
  65407. }
  65408. };
  65409. return VideoTexture;
  65410. }(BABYLON.Texture));
  65411. BABYLON.VideoTexture = VideoTexture;
  65412. })(BABYLON || (BABYLON = {}));
  65413. //# sourceMappingURL=babylon.videoTexture.js.map
  65414. var BABYLON;
  65415. (function (BABYLON) {
  65416. var RawTexture = /** @class */ (function (_super) {
  65417. __extends(RawTexture, _super);
  65418. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65419. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65420. if (invertY === void 0) { invertY = false; }
  65421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65422. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65423. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65424. _this.format = format;
  65425. _this._engine = scene.getEngine();
  65426. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65427. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65428. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65429. return _this;
  65430. }
  65431. RawTexture.prototype.update = function (data) {
  65432. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65433. };
  65434. // Statics
  65435. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65436. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65437. if (invertY === void 0) { invertY = false; }
  65438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65439. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65440. };
  65441. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65442. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65443. if (invertY === void 0) { invertY = false; }
  65444. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65445. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65446. };
  65447. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65448. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65449. if (invertY === void 0) { invertY = false; }
  65450. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65451. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65452. };
  65453. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65454. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65455. if (invertY === void 0) { invertY = false; }
  65456. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65457. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65458. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65459. };
  65460. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65461. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65462. if (invertY === void 0) { invertY = false; }
  65463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65464. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65465. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65466. };
  65467. return RawTexture;
  65468. }(BABYLON.Texture));
  65469. BABYLON.RawTexture = RawTexture;
  65470. })(BABYLON || (BABYLON = {}));
  65471. //# sourceMappingURL=babylon.rawTexture.js.map
  65472. var BABYLON;
  65473. (function (BABYLON) {
  65474. /**
  65475. * Class used to store 3D textures containing user data
  65476. */
  65477. var RawTexture3D = /** @class */ (function (_super) {
  65478. __extends(RawTexture3D, _super);
  65479. /**
  65480. * Create a new RawTexture3D
  65481. * @param data defines the data of the texture
  65482. * @param width defines the width of the texture
  65483. * @param height defines the height of the texture
  65484. * @param depth defines the depth of the texture
  65485. * @param format defines the texture format to use
  65486. * @param scene defines the hosting scene
  65487. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65488. * @param invertY defines if texture must be stored with Y axis inverted
  65489. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65490. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65491. */
  65492. function RawTexture3D(data, width, height, depth,
  65493. /** Gets or sets the texture format to use */
  65494. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65495. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65496. if (invertY === void 0) { invertY = false; }
  65497. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65498. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65499. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65500. _this.format = format;
  65501. _this._engine = scene.getEngine();
  65502. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65503. _this.is3D = true;
  65504. return _this;
  65505. }
  65506. /**
  65507. * Update the texture with new data
  65508. * @param data defines the data to store in the texture
  65509. */
  65510. RawTexture3D.prototype.update = function (data) {
  65511. if (!this._texture) {
  65512. return;
  65513. }
  65514. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65515. };
  65516. return RawTexture3D;
  65517. }(BABYLON.Texture));
  65518. BABYLON.RawTexture3D = RawTexture3D;
  65519. })(BABYLON || (BABYLON = {}));
  65520. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65521. var BABYLON;
  65522. (function (BABYLON) {
  65523. /**
  65524. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65525. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65526. */
  65527. var PostProcess = /** @class */ (function () {
  65528. /**
  65529. * Creates a new instance PostProcess
  65530. * @param name The name of the PostProcess.
  65531. * @param fragmentUrl The url of the fragment shader to be used.
  65532. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65533. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65534. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65535. * @param camera The camera to apply the render pass to.
  65536. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65537. * @param engine The engine which the post process will be applied. (default: current engine)
  65538. * @param reusable If the post process can be reused on the same frame. (default: false)
  65539. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65540. * @param textureType Type of textures used when performing the post process. (default: 0)
  65541. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65542. * @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
  65543. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65544. */
  65545. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65546. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65547. if (defines === void 0) { defines = null; }
  65548. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65549. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65550. if (blockCompilation === void 0) { blockCompilation = false; }
  65551. this.name = name;
  65552. /**
  65553. * Width of the texture to apply the post process on
  65554. */
  65555. this.width = -1;
  65556. /**
  65557. * Height of the texture to apply the post process on
  65558. */
  65559. this.height = -1;
  65560. /**
  65561. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65562. */
  65563. this._outputTexture = null;
  65564. /**
  65565. * If the buffer needs to be cleared before applying the post process. (default: true)
  65566. * Should be set to false if shader will overwrite all previous pixels.
  65567. */
  65568. this.autoClear = true;
  65569. /**
  65570. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65571. */
  65572. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65573. /**
  65574. * Animations to be used for the post processing
  65575. */
  65576. this.animations = new Array();
  65577. /**
  65578. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65579. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65580. */
  65581. this.enablePixelPerfectMode = false;
  65582. /**
  65583. * Force the postprocess to be applied without taking in account viewport
  65584. */
  65585. this.forceFullscreenViewport = true;
  65586. /**
  65587. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65588. *
  65589. * | Value | Type | Description |
  65590. * | ----- | ----------------------------------- | ----------- |
  65591. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65592. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65593. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65594. *
  65595. */
  65596. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65597. /**
  65598. * Force textures to be a power of two (default: false)
  65599. */
  65600. this.alwaysForcePOT = false;
  65601. /**
  65602. * Number of sample textures (default: 1)
  65603. */
  65604. this.samples = 1;
  65605. /**
  65606. * Modify the scale of the post process to be the same as the viewport (default: false)
  65607. */
  65608. this.adaptScaleToCurrentViewport = false;
  65609. this._reusable = false;
  65610. /**
  65611. * Smart array of input and output textures for the post process.
  65612. */
  65613. this._textures = new BABYLON.SmartArray(2);
  65614. /**
  65615. * The index in _textures that corresponds to the output texture.
  65616. */
  65617. this._currentRenderTextureInd = 0;
  65618. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65619. this._texelSize = BABYLON.Vector2.Zero();
  65620. // Events
  65621. /**
  65622. * An event triggered when the postprocess is activated.
  65623. */
  65624. this.onActivateObservable = new BABYLON.Observable();
  65625. /**
  65626. * An event triggered when the postprocess changes its size.
  65627. */
  65628. this.onSizeChangedObservable = new BABYLON.Observable();
  65629. /**
  65630. * An event triggered when the postprocess applies its effect.
  65631. */
  65632. this.onApplyObservable = new BABYLON.Observable();
  65633. /**
  65634. * An event triggered before rendering the postprocess
  65635. */
  65636. this.onBeforeRenderObservable = new BABYLON.Observable();
  65637. /**
  65638. * An event triggered after rendering the postprocess
  65639. */
  65640. this.onAfterRenderObservable = new BABYLON.Observable();
  65641. if (camera != null) {
  65642. this._camera = camera;
  65643. this._scene = camera.getScene();
  65644. camera.attachPostProcess(this);
  65645. this._engine = this._scene.getEngine();
  65646. this._scene.postProcesses.push(this);
  65647. }
  65648. else if (engine) {
  65649. this._engine = engine;
  65650. this._engine.postProcesses.push(this);
  65651. }
  65652. this._options = options;
  65653. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65654. this._reusable = reusable || false;
  65655. this._textureType = textureType;
  65656. this._samplers = samplers || [];
  65657. this._samplers.push("textureSampler");
  65658. this._fragmentUrl = fragmentUrl;
  65659. this._vertexUrl = vertexUrl;
  65660. this._parameters = parameters || [];
  65661. this._parameters.push("scale");
  65662. this._indexParameters = indexParameters;
  65663. if (!blockCompilation) {
  65664. this.updateEffect(defines);
  65665. }
  65666. }
  65667. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65668. /**
  65669. * A function that is added to the onActivateObservable
  65670. */
  65671. set: function (callback) {
  65672. if (this._onActivateObserver) {
  65673. this.onActivateObservable.remove(this._onActivateObserver);
  65674. }
  65675. if (callback) {
  65676. this._onActivateObserver = this.onActivateObservable.add(callback);
  65677. }
  65678. },
  65679. enumerable: true,
  65680. configurable: true
  65681. });
  65682. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65683. /**
  65684. * A function that is added to the onSizeChangedObservable
  65685. */
  65686. set: function (callback) {
  65687. if (this._onSizeChangedObserver) {
  65688. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65689. }
  65690. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65691. },
  65692. enumerable: true,
  65693. configurable: true
  65694. });
  65695. Object.defineProperty(PostProcess.prototype, "onApply", {
  65696. /**
  65697. * A function that is added to the onApplyObservable
  65698. */
  65699. set: function (callback) {
  65700. if (this._onApplyObserver) {
  65701. this.onApplyObservable.remove(this._onApplyObserver);
  65702. }
  65703. this._onApplyObserver = this.onApplyObservable.add(callback);
  65704. },
  65705. enumerable: true,
  65706. configurable: true
  65707. });
  65708. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65709. /**
  65710. * A function that is added to the onBeforeRenderObservable
  65711. */
  65712. set: function (callback) {
  65713. if (this._onBeforeRenderObserver) {
  65714. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65715. }
  65716. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65717. },
  65718. enumerable: true,
  65719. configurable: true
  65720. });
  65721. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65722. /**
  65723. * A function that is added to the onAfterRenderObservable
  65724. */
  65725. set: function (callback) {
  65726. if (this._onAfterRenderObserver) {
  65727. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65728. }
  65729. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65730. },
  65731. enumerable: true,
  65732. configurable: true
  65733. });
  65734. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65735. /**
  65736. * 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
  65737. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65738. */
  65739. get: function () {
  65740. return this._textures.data[this._currentRenderTextureInd];
  65741. },
  65742. set: function (value) {
  65743. this._forcedOutputTexture = value;
  65744. },
  65745. enumerable: true,
  65746. configurable: true
  65747. });
  65748. /**
  65749. * Gets the camera which post process is applied to.
  65750. * @returns The camera the post process is applied to.
  65751. */
  65752. PostProcess.prototype.getCamera = function () {
  65753. return this._camera;
  65754. };
  65755. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65756. /**
  65757. * Gets the texel size of the postprocess.
  65758. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65759. */
  65760. get: function () {
  65761. if (this._shareOutputWithPostProcess) {
  65762. return this._shareOutputWithPostProcess.texelSize;
  65763. }
  65764. if (this._forcedOutputTexture) {
  65765. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65766. }
  65767. return this._texelSize;
  65768. },
  65769. enumerable: true,
  65770. configurable: true
  65771. });
  65772. /**
  65773. * Gets the engine which this post process belongs to.
  65774. * @returns The engine the post process was enabled with.
  65775. */
  65776. PostProcess.prototype.getEngine = function () {
  65777. return this._engine;
  65778. };
  65779. /**
  65780. * The effect that is created when initializing the post process.
  65781. * @returns The created effect corrisponding the the postprocess.
  65782. */
  65783. PostProcess.prototype.getEffect = function () {
  65784. return this._effect;
  65785. };
  65786. /**
  65787. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65788. * @param postProcess The post process to share the output with.
  65789. * @returns This post process.
  65790. */
  65791. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65792. this._disposeTextures();
  65793. this._shareOutputWithPostProcess = postProcess;
  65794. return this;
  65795. };
  65796. /**
  65797. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65798. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65799. */
  65800. PostProcess.prototype.useOwnOutput = function () {
  65801. if (this._textures.length == 0) {
  65802. this._textures = new BABYLON.SmartArray(2);
  65803. }
  65804. this._shareOutputWithPostProcess = null;
  65805. };
  65806. /**
  65807. * Updates the effect with the current post process compile time values and recompiles the shader.
  65808. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65809. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65810. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65811. * @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
  65812. * @param onCompiled Called when the shader has been compiled.
  65813. * @param onError Called if there is an error when compiling a shader.
  65814. */
  65815. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65816. if (defines === void 0) { defines = null; }
  65817. if (uniforms === void 0) { uniforms = null; }
  65818. if (samplers === void 0) { samplers = null; }
  65819. 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);
  65820. };
  65821. /**
  65822. * The post process is reusable if it can be used multiple times within one frame.
  65823. * @returns If the post process is reusable
  65824. */
  65825. PostProcess.prototype.isReusable = function () {
  65826. return this._reusable;
  65827. };
  65828. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65829. PostProcess.prototype.markTextureDirty = function () {
  65830. this.width = -1;
  65831. };
  65832. /**
  65833. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65834. * 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.
  65835. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65836. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65837. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65838. * @returns The target texture that was bound to be written to.
  65839. */
  65840. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65841. var _this = this;
  65842. if (sourceTexture === void 0) { sourceTexture = null; }
  65843. camera = camera || this._camera;
  65844. var scene = camera.getScene();
  65845. var engine = scene.getEngine();
  65846. var maxSize = engine.getCaps().maxTextureSize;
  65847. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65848. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65849. // 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
  65850. var webVRCamera = camera.parent;
  65851. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65852. requiredWidth /= 2;
  65853. }
  65854. var desiredWidth = (this._options.width || requiredWidth);
  65855. var desiredHeight = this._options.height || requiredHeight;
  65856. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65857. if (this.adaptScaleToCurrentViewport) {
  65858. var currentViewport = engine.currentViewport;
  65859. if (currentViewport) {
  65860. desiredWidth *= currentViewport.width;
  65861. desiredHeight *= currentViewport.height;
  65862. }
  65863. }
  65864. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65865. if (!this._options.width) {
  65866. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65867. }
  65868. if (!this._options.height) {
  65869. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65870. }
  65871. }
  65872. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65873. if (this._textures.length > 0) {
  65874. for (var i = 0; i < this._textures.length; i++) {
  65875. this._engine._releaseTexture(this._textures.data[i]);
  65876. }
  65877. this._textures.reset();
  65878. }
  65879. this.width = desiredWidth;
  65880. this.height = desiredHeight;
  65881. var textureSize = { width: this.width, height: this.height };
  65882. var textureOptions = {
  65883. generateMipMaps: false,
  65884. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65885. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65886. samplingMode: this.renderTargetSamplingMode,
  65887. type: this._textureType
  65888. };
  65889. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65890. if (this._reusable) {
  65891. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65892. }
  65893. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65894. this.onSizeChangedObservable.notifyObservers(this);
  65895. }
  65896. this._textures.forEach(function (texture) {
  65897. if (texture.samples !== _this.samples) {
  65898. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65899. }
  65900. });
  65901. }
  65902. var target;
  65903. if (this._shareOutputWithPostProcess) {
  65904. target = this._shareOutputWithPostProcess.inputTexture;
  65905. }
  65906. else if (this._forcedOutputTexture) {
  65907. target = this._forcedOutputTexture;
  65908. this.width = this._forcedOutputTexture.width;
  65909. this.height = this._forcedOutputTexture.height;
  65910. }
  65911. else {
  65912. target = this.inputTexture;
  65913. }
  65914. // Bind the input of this post process to be used as the output of the previous post process.
  65915. if (this.enablePixelPerfectMode) {
  65916. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65917. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65918. }
  65919. else {
  65920. this._scaleRatio.copyFromFloats(1, 1);
  65921. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65922. }
  65923. this.onActivateObservable.notifyObservers(camera);
  65924. // Clear
  65925. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65926. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65927. }
  65928. if (this._reusable) {
  65929. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65930. }
  65931. return target;
  65932. };
  65933. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65934. /**
  65935. * If the post process is supported.
  65936. */
  65937. get: function () {
  65938. return this._effect.isSupported;
  65939. },
  65940. enumerable: true,
  65941. configurable: true
  65942. });
  65943. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65944. /**
  65945. * The aspect ratio of the output texture.
  65946. */
  65947. get: function () {
  65948. if (this._shareOutputWithPostProcess) {
  65949. return this._shareOutputWithPostProcess.aspectRatio;
  65950. }
  65951. if (this._forcedOutputTexture) {
  65952. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65953. }
  65954. return this.width / this.height;
  65955. },
  65956. enumerable: true,
  65957. configurable: true
  65958. });
  65959. /**
  65960. * Get a value indicating if the post-process is ready to be used
  65961. * @returns true if the post-process is ready (shader is compiled)
  65962. */
  65963. PostProcess.prototype.isReady = function () {
  65964. return this._effect && this._effect.isReady();
  65965. };
  65966. /**
  65967. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65968. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65969. */
  65970. PostProcess.prototype.apply = function () {
  65971. // Check
  65972. if (!this._effect || !this._effect.isReady())
  65973. return null;
  65974. // States
  65975. this._engine.enableEffect(this._effect);
  65976. this._engine.setState(false);
  65977. this._engine.setDepthBuffer(false);
  65978. this._engine.setDepthWrite(false);
  65979. // Alpha
  65980. this._engine.setAlphaMode(this.alphaMode);
  65981. if (this.alphaConstants) {
  65982. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65983. }
  65984. // Bind the output texture of the preivous post process as the input to this post process.
  65985. var source;
  65986. if (this._shareOutputWithPostProcess) {
  65987. source = this._shareOutputWithPostProcess.inputTexture;
  65988. }
  65989. else if (this._forcedOutputTexture) {
  65990. source = this._forcedOutputTexture;
  65991. }
  65992. else {
  65993. source = this.inputTexture;
  65994. }
  65995. this._effect._bindTexture("textureSampler", source);
  65996. // Parameters
  65997. this._effect.setVector2("scale", this._scaleRatio);
  65998. this.onApplyObservable.notifyObservers(this._effect);
  65999. return this._effect;
  66000. };
  66001. PostProcess.prototype._disposeTextures = function () {
  66002. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  66003. return;
  66004. }
  66005. if (this._textures.length > 0) {
  66006. for (var i = 0; i < this._textures.length; i++) {
  66007. this._engine._releaseTexture(this._textures.data[i]);
  66008. }
  66009. }
  66010. this._textures.dispose();
  66011. };
  66012. /**
  66013. * Disposes the post process.
  66014. * @param camera The camera to dispose the post process on.
  66015. */
  66016. PostProcess.prototype.dispose = function (camera) {
  66017. camera = camera || this._camera;
  66018. this._disposeTextures();
  66019. if (this._scene) {
  66020. var index_1 = this._scene.postProcesses.indexOf(this);
  66021. if (index_1 !== -1) {
  66022. this._scene.postProcesses.splice(index_1, 1);
  66023. }
  66024. }
  66025. else {
  66026. var index_2 = this._engine.postProcesses.indexOf(this);
  66027. if (index_2 !== -1) {
  66028. this._engine.postProcesses.splice(index_2, 1);
  66029. }
  66030. }
  66031. if (!camera) {
  66032. return;
  66033. }
  66034. camera.detachPostProcess(this);
  66035. var index = camera._postProcesses.indexOf(this);
  66036. if (index === 0 && camera._postProcesses.length > 0) {
  66037. var firstPostProcess = this._camera._getFirstPostProcess();
  66038. if (firstPostProcess) {
  66039. firstPostProcess.markTextureDirty();
  66040. }
  66041. }
  66042. this.onActivateObservable.clear();
  66043. this.onAfterRenderObservable.clear();
  66044. this.onApplyObservable.clear();
  66045. this.onBeforeRenderObservable.clear();
  66046. this.onSizeChangedObservable.clear();
  66047. };
  66048. return PostProcess;
  66049. }());
  66050. BABYLON.PostProcess = PostProcess;
  66051. })(BABYLON || (BABYLON = {}));
  66052. //# sourceMappingURL=babylon.postProcess.js.map
  66053. var BABYLON;
  66054. (function (BABYLON) {
  66055. var PassPostProcess = /** @class */ (function (_super) {
  66056. __extends(PassPostProcess, _super);
  66057. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66058. if (camera === void 0) { camera = null; }
  66059. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66060. if (blockCompilation === void 0) { blockCompilation = false; }
  66061. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66062. }
  66063. return PassPostProcess;
  66064. }(BABYLON.PostProcess));
  66065. BABYLON.PassPostProcess = PassPostProcess;
  66066. })(BABYLON || (BABYLON = {}));
  66067. //# sourceMappingURL=babylon.passPostProcess.js.map
  66068. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66069. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66070. s = arguments[i];
  66071. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66072. t[p] = s[p];
  66073. }
  66074. return t;
  66075. };
  66076. var BABYLON;
  66077. (function (BABYLON) {
  66078. /**
  66079. * Default implementation IShadowGenerator.
  66080. * This is the main object responsible of generating shadows in the framework.
  66081. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66082. */
  66083. var ShadowGenerator = /** @class */ (function () {
  66084. /**
  66085. * Creates a ShadowGenerator object.
  66086. * A ShadowGenerator is the required tool to use the shadows.
  66087. * Each light casting shadows needs to use its own ShadowGenerator.
  66088. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66089. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66090. * @param light The light object generating the shadows.
  66091. * @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.
  66092. */
  66093. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66094. this._bias = 0.00005;
  66095. this._normalBias = 0;
  66096. this._blurBoxOffset = 1;
  66097. this._blurScale = 2;
  66098. this._blurKernel = 1;
  66099. this._useKernelBlur = false;
  66100. this._filter = ShadowGenerator.FILTER_NONE;
  66101. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66102. this._contactHardeningLightSizeUVRatio = 0.1;
  66103. this._darkness = 0;
  66104. this._transparencyShadow = false;
  66105. /**
  66106. * Controls the extent to which the shadows fade out at the edge of the frustum
  66107. * Used only by directionals and spots
  66108. */
  66109. this.frustumEdgeFalloff = 0;
  66110. /**
  66111. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66112. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66113. * It might on the other hand introduce peter panning.
  66114. */
  66115. this.forceBackFacesOnly = false;
  66116. this._lightDirection = BABYLON.Vector3.Zero();
  66117. this._viewMatrix = BABYLON.Matrix.Zero();
  66118. this._projectionMatrix = BABYLON.Matrix.Zero();
  66119. this._transformMatrix = BABYLON.Matrix.Zero();
  66120. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66121. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66122. this._currentFaceIndex = 0;
  66123. this._currentFaceIndexCache = 0;
  66124. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66125. this._mapSize = mapSize;
  66126. this._light = light;
  66127. this._scene = light.getScene();
  66128. light._shadowGenerator = this;
  66129. // Texture type fallback from float to int if not supported.
  66130. var caps = this._scene.getEngine().getCaps();
  66131. if (!useFullFloatFirst) {
  66132. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66133. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66134. }
  66135. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66136. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66137. }
  66138. else {
  66139. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66140. }
  66141. }
  66142. else {
  66143. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66144. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66145. }
  66146. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66147. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66148. }
  66149. else {
  66150. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66151. }
  66152. }
  66153. this._initializeGenerator();
  66154. this._applyFilterValues();
  66155. }
  66156. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66157. /**
  66158. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66159. */
  66160. get: function () {
  66161. return this._bias;
  66162. },
  66163. /**
  66164. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66165. */
  66166. set: function (bias) {
  66167. this._bias = bias;
  66168. },
  66169. enumerable: true,
  66170. configurable: true
  66171. });
  66172. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66173. /**
  66174. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66175. */
  66176. get: function () {
  66177. return this._normalBias;
  66178. },
  66179. /**
  66180. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66181. */
  66182. set: function (normalBias) {
  66183. this._normalBias = normalBias;
  66184. },
  66185. enumerable: true,
  66186. configurable: true
  66187. });
  66188. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66189. /**
  66190. * Gets the blur box offset: offset applied during the blur pass.
  66191. * Only usefull if useKernelBlur = false
  66192. */
  66193. get: function () {
  66194. return this._blurBoxOffset;
  66195. },
  66196. /**
  66197. * Sets the blur box offset: offset applied during the blur pass.
  66198. * Only usefull if useKernelBlur = false
  66199. */
  66200. set: function (value) {
  66201. if (this._blurBoxOffset === value) {
  66202. return;
  66203. }
  66204. this._blurBoxOffset = value;
  66205. this._disposeBlurPostProcesses();
  66206. },
  66207. enumerable: true,
  66208. configurable: true
  66209. });
  66210. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66211. /**
  66212. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66213. * 2 means half of the size.
  66214. */
  66215. get: function () {
  66216. return this._blurScale;
  66217. },
  66218. /**
  66219. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66220. * 2 means half of the size.
  66221. */
  66222. set: function (value) {
  66223. if (this._blurScale === value) {
  66224. return;
  66225. }
  66226. this._blurScale = value;
  66227. this._disposeBlurPostProcesses();
  66228. },
  66229. enumerable: true,
  66230. configurable: true
  66231. });
  66232. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66233. /**
  66234. * Gets the blur kernel: kernel size of the blur pass.
  66235. * Only usefull if useKernelBlur = true
  66236. */
  66237. get: function () {
  66238. return this._blurKernel;
  66239. },
  66240. /**
  66241. * Sets the blur kernel: kernel size of the blur pass.
  66242. * Only usefull if useKernelBlur = true
  66243. */
  66244. set: function (value) {
  66245. if (this._blurKernel === value) {
  66246. return;
  66247. }
  66248. this._blurKernel = value;
  66249. this._disposeBlurPostProcesses();
  66250. },
  66251. enumerable: true,
  66252. configurable: true
  66253. });
  66254. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66255. /**
  66256. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66257. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66258. */
  66259. get: function () {
  66260. return this._useKernelBlur;
  66261. },
  66262. /**
  66263. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66264. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66265. */
  66266. set: function (value) {
  66267. if (this._useKernelBlur === value) {
  66268. return;
  66269. }
  66270. this._useKernelBlur = value;
  66271. this._disposeBlurPostProcesses();
  66272. },
  66273. enumerable: true,
  66274. configurable: true
  66275. });
  66276. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66277. /**
  66278. * Gets the depth scale used in ESM mode.
  66279. */
  66280. get: function () {
  66281. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66282. },
  66283. /**
  66284. * Sets the depth scale used in ESM mode.
  66285. * This can override the scale stored on the light.
  66286. */
  66287. set: function (value) {
  66288. this._depthScale = value;
  66289. },
  66290. enumerable: true,
  66291. configurable: true
  66292. });
  66293. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66294. /**
  66295. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66296. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66297. */
  66298. get: function () {
  66299. return this._filter;
  66300. },
  66301. /**
  66302. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66303. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66304. */
  66305. set: function (value) {
  66306. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66307. if (this._light.needCube()) {
  66308. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66309. this.useExponentialShadowMap = true;
  66310. return;
  66311. }
  66312. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66313. this.useCloseExponentialShadowMap = true;
  66314. return;
  66315. }
  66316. // PCF on cubemap would also be expensive
  66317. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66318. this.usePoissonSampling = true;
  66319. return;
  66320. }
  66321. }
  66322. // Weblg1 fallback for PCF.
  66323. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66324. if (this._scene.getEngine().webGLVersion === 1) {
  66325. this.usePoissonSampling = true;
  66326. return;
  66327. }
  66328. }
  66329. if (this._filter === value) {
  66330. return;
  66331. }
  66332. this._filter = value;
  66333. this._disposeBlurPostProcesses();
  66334. this._applyFilterValues();
  66335. this._light._markMeshesAsLightDirty();
  66336. },
  66337. enumerable: true,
  66338. configurable: true
  66339. });
  66340. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66341. /**
  66342. * Gets if the current filter is set to Poisson Sampling.
  66343. */
  66344. get: function () {
  66345. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66346. },
  66347. /**
  66348. * Sets the current filter to Poisson Sampling.
  66349. */
  66350. set: function (value) {
  66351. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66352. return;
  66353. }
  66354. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66355. },
  66356. enumerable: true,
  66357. configurable: true
  66358. });
  66359. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66360. /**
  66361. * Gets if the current filter is set to VSM.
  66362. * DEPRECATED. Should use useExponentialShadowMap instead.
  66363. */
  66364. get: function () {
  66365. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66366. return this.useExponentialShadowMap;
  66367. },
  66368. /**
  66369. * Sets the current filter is to VSM.
  66370. * DEPRECATED. Should use useExponentialShadowMap instead.
  66371. */
  66372. set: function (value) {
  66373. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66374. this.useExponentialShadowMap = value;
  66375. },
  66376. enumerable: true,
  66377. configurable: true
  66378. });
  66379. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66380. /**
  66381. * Gets if the current filter is set to blurred VSM.
  66382. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66383. */
  66384. get: function () {
  66385. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66386. return this.useBlurExponentialShadowMap;
  66387. },
  66388. /**
  66389. * Sets the current filter is to blurred VSM.
  66390. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66391. */
  66392. set: function (value) {
  66393. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66394. this.useBlurExponentialShadowMap = value;
  66395. },
  66396. enumerable: true,
  66397. configurable: true
  66398. });
  66399. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66400. /**
  66401. * Gets if the current filter is set to ESM.
  66402. */
  66403. get: function () {
  66404. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66405. },
  66406. /**
  66407. * Sets the current filter is to ESM.
  66408. */
  66409. set: function (value) {
  66410. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66411. return;
  66412. }
  66413. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66414. },
  66415. enumerable: true,
  66416. configurable: true
  66417. });
  66418. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66419. /**
  66420. * Gets if the current filter is set to filtered ESM.
  66421. */
  66422. get: function () {
  66423. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66424. },
  66425. /**
  66426. * Gets if the current filter is set to filtered ESM.
  66427. */
  66428. set: function (value) {
  66429. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66430. return;
  66431. }
  66432. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66433. },
  66434. enumerable: true,
  66435. configurable: true
  66436. });
  66437. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66438. /**
  66439. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66440. * exponential to prevent steep falloff artifacts).
  66441. */
  66442. get: function () {
  66443. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66444. },
  66445. /**
  66446. * Sets the current filter to "close ESM" (using the inverse of the
  66447. * exponential to prevent steep falloff artifacts).
  66448. */
  66449. set: function (value) {
  66450. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66451. return;
  66452. }
  66453. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66454. },
  66455. enumerable: true,
  66456. configurable: true
  66457. });
  66458. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66459. /**
  66460. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66461. * exponential to prevent steep falloff artifacts).
  66462. */
  66463. get: function () {
  66464. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66465. },
  66466. /**
  66467. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66468. * exponential to prevent steep falloff artifacts).
  66469. */
  66470. set: function (value) {
  66471. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66472. return;
  66473. }
  66474. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66475. },
  66476. enumerable: true,
  66477. configurable: true
  66478. });
  66479. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66480. /**
  66481. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66482. */
  66483. get: function () {
  66484. return this.filter === ShadowGenerator.FILTER_PCF;
  66485. },
  66486. /**
  66487. * Sets the current filter to "PCF" (percentage closer filtering).
  66488. */
  66489. set: function (value) {
  66490. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66491. return;
  66492. }
  66493. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66494. },
  66495. enumerable: true,
  66496. configurable: true
  66497. });
  66498. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66499. /**
  66500. * Gets the PCF or PCSS Quality.
  66501. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66502. */
  66503. get: function () {
  66504. return this._filteringQuality;
  66505. },
  66506. /**
  66507. * Sets the PCF or PCSS Quality.
  66508. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66509. */
  66510. set: function (filteringQuality) {
  66511. this._filteringQuality = filteringQuality;
  66512. },
  66513. enumerable: true,
  66514. configurable: true
  66515. });
  66516. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66517. /**
  66518. * Gets if the current filter is set to "PCSS" (contact hardening).
  66519. */
  66520. get: function () {
  66521. return this.filter === ShadowGenerator.FILTER_PCSS;
  66522. },
  66523. /**
  66524. * Sets the current filter to "PCSS" (contact hardening).
  66525. */
  66526. set: function (value) {
  66527. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66528. return;
  66529. }
  66530. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66531. },
  66532. enumerable: true,
  66533. configurable: true
  66534. });
  66535. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66536. /**
  66537. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66538. * Using a ratio helps keeping shape stability independently of the map size.
  66539. *
  66540. * It does not account for the light projection as it was having too much
  66541. * instability during the light setup or during light position changes.
  66542. *
  66543. * Only valid if useContactHardeningShadow is true.
  66544. */
  66545. get: function () {
  66546. return this._contactHardeningLightSizeUVRatio;
  66547. },
  66548. /**
  66549. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66550. * Using a ratio helps keeping shape stability independently of the map size.
  66551. *
  66552. * It does not account for the light projection as it was having too much
  66553. * instability during the light setup or during light position changes.
  66554. *
  66555. * Only valid if useContactHardeningShadow is true.
  66556. */
  66557. set: function (contactHardeningLightSizeUVRatio) {
  66558. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66559. },
  66560. enumerable: true,
  66561. configurable: true
  66562. });
  66563. /**
  66564. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66565. * 0 means strongest and 1 would means no shadow.
  66566. * @returns the darkness.
  66567. */
  66568. ShadowGenerator.prototype.getDarkness = function () {
  66569. return this._darkness;
  66570. };
  66571. /**
  66572. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66573. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66574. * @returns the shadow generator allowing fluent coding.
  66575. */
  66576. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66577. if (darkness >= 1.0)
  66578. this._darkness = 1.0;
  66579. else if (darkness <= 0.0)
  66580. this._darkness = 0.0;
  66581. else
  66582. this._darkness = darkness;
  66583. return this;
  66584. };
  66585. /**
  66586. * Sets the ability to have transparent shadow (boolean).
  66587. * @param transparent True if transparent else False
  66588. * @returns the shadow generator allowing fluent coding
  66589. */
  66590. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66591. this._transparencyShadow = transparent;
  66592. return this;
  66593. };
  66594. /**
  66595. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66596. * @returns The render target texture if present otherwise, null
  66597. */
  66598. ShadowGenerator.prototype.getShadowMap = function () {
  66599. return this._shadowMap;
  66600. };
  66601. /**
  66602. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66603. * @returns The render target texture if the shadow map is present otherwise, null
  66604. */
  66605. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66606. if (this._shadowMap2) {
  66607. return this._shadowMap2;
  66608. }
  66609. return this._shadowMap;
  66610. };
  66611. /**
  66612. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66613. * @param mesh Mesh to add
  66614. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66615. * @returns the Shadow Generator itself
  66616. */
  66617. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66618. if (includeDescendants === void 0) { includeDescendants = true; }
  66619. if (!this._shadowMap) {
  66620. return this;
  66621. }
  66622. if (!this._shadowMap.renderList) {
  66623. this._shadowMap.renderList = [];
  66624. }
  66625. this._shadowMap.renderList.push(mesh);
  66626. if (includeDescendants) {
  66627. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66628. }
  66629. return this;
  66630. var _a;
  66631. };
  66632. /**
  66633. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66634. * @param mesh Mesh to remove
  66635. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66636. * @returns the Shadow Generator itself
  66637. */
  66638. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66639. if (includeDescendants === void 0) { includeDescendants = true; }
  66640. if (!this._shadowMap || !this._shadowMap.renderList) {
  66641. return this;
  66642. }
  66643. var index = this._shadowMap.renderList.indexOf(mesh);
  66644. if (index !== -1) {
  66645. this._shadowMap.renderList.splice(index, 1);
  66646. }
  66647. if (includeDescendants) {
  66648. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66649. var child = _a[_i];
  66650. this.removeShadowCaster(child);
  66651. }
  66652. }
  66653. return this;
  66654. };
  66655. /**
  66656. * Returns the associated light object.
  66657. * @returns the light generating the shadow
  66658. */
  66659. ShadowGenerator.prototype.getLight = function () {
  66660. return this._light;
  66661. };
  66662. ShadowGenerator.prototype._initializeGenerator = function () {
  66663. this._light._markMeshesAsLightDirty();
  66664. this._initializeShadowMap();
  66665. };
  66666. ShadowGenerator.prototype._initializeShadowMap = function () {
  66667. var _this = this;
  66668. // Render target
  66669. var engine = this._scene.getEngine();
  66670. if (engine.webGLVersion > 1) {
  66671. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66672. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66673. }
  66674. else {
  66675. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66676. }
  66677. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66678. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66679. this._shadowMap.anisotropicFilteringLevel = 1;
  66680. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66681. this._shadowMap.renderParticles = false;
  66682. this._shadowMap.ignoreCameraViewport = true;
  66683. // Record Face Index before render.
  66684. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66685. _this._currentFaceIndex = faceIndex;
  66686. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66687. engine.setColorWrite(false);
  66688. }
  66689. });
  66690. // Custom render function.
  66691. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66692. // Blur if required afer render.
  66693. this._shadowMap.onAfterUnbindObservable.add(function () {
  66694. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66695. engine.setColorWrite(true);
  66696. }
  66697. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66698. return;
  66699. }
  66700. var shadowMap = _this.getShadowMapForRendering();
  66701. if (shadowMap) {
  66702. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66703. }
  66704. });
  66705. // Clear according to the chosen filter.
  66706. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66707. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66708. this._shadowMap.onClearObservable.add(function (engine) {
  66709. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66710. engine.clear(clearOne, false, true, false);
  66711. }
  66712. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66713. engine.clear(clearZero, true, true, false);
  66714. }
  66715. else {
  66716. engine.clear(clearOne, true, true, false);
  66717. }
  66718. });
  66719. };
  66720. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66721. var _this = this;
  66722. var engine = this._scene.getEngine();
  66723. var targetSize = this._mapSize / this.blurScale;
  66724. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66725. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66726. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66727. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66728. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66729. }
  66730. if (this.useKernelBlur) {
  66731. 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);
  66732. this._kernelBlurXPostprocess.width = targetSize;
  66733. this._kernelBlurXPostprocess.height = targetSize;
  66734. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66735. effect.setTexture("textureSampler", _this._shadowMap);
  66736. });
  66737. 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);
  66738. this._kernelBlurXPostprocess.autoClear = false;
  66739. this._kernelBlurYPostprocess.autoClear = false;
  66740. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66741. this._kernelBlurXPostprocess.packedFloat = true;
  66742. this._kernelBlurYPostprocess.packedFloat = true;
  66743. }
  66744. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66745. }
  66746. else {
  66747. 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);
  66748. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66749. effect.setFloat2("screenSize", targetSize, targetSize);
  66750. effect.setTexture("textureSampler", _this._shadowMap);
  66751. });
  66752. this._boxBlurPostprocess.autoClear = false;
  66753. this._blurPostProcesses = [this._boxBlurPostprocess];
  66754. }
  66755. };
  66756. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66757. var index;
  66758. var engine = this._scene.getEngine();
  66759. if (depthOnlySubMeshes.length) {
  66760. engine.setColorWrite(false);
  66761. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66762. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66763. }
  66764. engine.setColorWrite(true);
  66765. }
  66766. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66767. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66768. }
  66769. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66770. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66771. }
  66772. if (this._transparencyShadow) {
  66773. for (index = 0; index < transparentSubMeshes.length; index++) {
  66774. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66775. }
  66776. }
  66777. };
  66778. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66779. var _this = this;
  66780. var mesh = subMesh.getRenderingMesh();
  66781. var scene = this._scene;
  66782. var engine = scene.getEngine();
  66783. var material = subMesh.getMaterial();
  66784. if (!material) {
  66785. return;
  66786. }
  66787. // Culling
  66788. engine.setState(material.backFaceCulling);
  66789. // Managing instances
  66790. var batch = mesh._getInstancesRenderList(subMesh._id);
  66791. if (batch.mustReturn) {
  66792. return;
  66793. }
  66794. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66795. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66796. engine.enableEffect(this._effect);
  66797. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66798. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66799. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66800. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66801. this._effect.setVector3("lightData", this._cachedDirection);
  66802. }
  66803. else {
  66804. this._effect.setVector3("lightData", this._cachedPosition);
  66805. }
  66806. if (scene.activeCamera) {
  66807. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66808. }
  66809. // Alpha test
  66810. if (material && material.needAlphaTesting()) {
  66811. var alphaTexture = material.getAlphaTestTexture();
  66812. if (alphaTexture) {
  66813. this._effect.setTexture("diffuseSampler", alphaTexture);
  66814. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66815. }
  66816. }
  66817. // Bones
  66818. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66819. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66820. }
  66821. // Morph targets
  66822. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66823. if (this.forceBackFacesOnly) {
  66824. engine.setState(true, 0, false, true);
  66825. }
  66826. // Draw
  66827. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66828. if (this.forceBackFacesOnly) {
  66829. engine.setState(true, 0, false, false);
  66830. }
  66831. }
  66832. else {
  66833. // Need to reset refresh rate of the shadowMap
  66834. if (this._shadowMap) {
  66835. this._shadowMap.resetRefreshCounter();
  66836. }
  66837. }
  66838. };
  66839. ShadowGenerator.prototype._applyFilterValues = function () {
  66840. if (!this._shadowMap) {
  66841. return;
  66842. }
  66843. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66844. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66845. }
  66846. else {
  66847. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66848. }
  66849. };
  66850. /**
  66851. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66852. * @param onCompiled Callback triggered at the and of the effects compilation
  66853. * @param options Sets of optional options forcing the compilation with different modes
  66854. */
  66855. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66856. var _this = this;
  66857. var localOptions = __assign({ useInstances: false }, options);
  66858. var shadowMap = this.getShadowMap();
  66859. if (!shadowMap) {
  66860. if (onCompiled) {
  66861. onCompiled(this);
  66862. }
  66863. return;
  66864. }
  66865. var renderList = shadowMap.renderList;
  66866. if (!renderList) {
  66867. if (onCompiled) {
  66868. onCompiled(this);
  66869. }
  66870. return;
  66871. }
  66872. var subMeshes = new Array();
  66873. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66874. var mesh = renderList_1[_i];
  66875. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66876. }
  66877. if (subMeshes.length === 0) {
  66878. if (onCompiled) {
  66879. onCompiled(this);
  66880. }
  66881. return;
  66882. }
  66883. var currentIndex = 0;
  66884. var checkReady = function () {
  66885. if (!_this._scene || !_this._scene.getEngine()) {
  66886. return;
  66887. }
  66888. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66889. currentIndex++;
  66890. if (currentIndex >= subMeshes.length) {
  66891. if (onCompiled) {
  66892. onCompiled(_this);
  66893. }
  66894. return;
  66895. }
  66896. }
  66897. setTimeout(checkReady, 16);
  66898. };
  66899. checkReady();
  66900. };
  66901. /**
  66902. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66903. * @param options Sets of optional options forcing the compilation with different modes
  66904. * @returns A promise that resolves when the compilation completes
  66905. */
  66906. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66907. var _this = this;
  66908. return new Promise(function (resolve) {
  66909. _this.forceCompilation(function () {
  66910. resolve();
  66911. }, options);
  66912. });
  66913. };
  66914. /**
  66915. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66916. * @param subMesh The submesh we want to render in the shadow map
  66917. * @param useInstances Defines wether will draw in the map using instances
  66918. * @returns true if ready otherwise, false
  66919. */
  66920. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66921. var defines = [];
  66922. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66923. defines.push("#define FLOAT");
  66924. }
  66925. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66926. defines.push("#define ESM");
  66927. }
  66928. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66929. defines.push("#define DEPTHTEXTURE");
  66930. }
  66931. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66932. var mesh = subMesh.getMesh();
  66933. var material = subMesh.getMaterial();
  66934. // Normal bias.
  66935. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66936. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66937. defines.push("#define NORMAL");
  66938. if (mesh.nonUniformScaling) {
  66939. defines.push("#define NONUNIFORMSCALING");
  66940. }
  66941. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66942. defines.push("#define DIRECTIONINLIGHTDATA");
  66943. }
  66944. }
  66945. // Alpha test
  66946. if (material && material.needAlphaTesting()) {
  66947. var alphaTexture = material.getAlphaTestTexture();
  66948. if (alphaTexture) {
  66949. defines.push("#define ALPHATEST");
  66950. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66951. attribs.push(BABYLON.VertexBuffer.UVKind);
  66952. defines.push("#define UV1");
  66953. }
  66954. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66955. if (alphaTexture.coordinatesIndex === 1) {
  66956. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66957. defines.push("#define UV2");
  66958. }
  66959. }
  66960. }
  66961. }
  66962. // Bones
  66963. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66964. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66965. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66966. if (mesh.numBoneInfluencers > 4) {
  66967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66969. }
  66970. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66971. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66972. }
  66973. else {
  66974. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66975. }
  66976. // Morph targets
  66977. var manager = mesh.morphTargetManager;
  66978. var morphInfluencers = 0;
  66979. if (manager) {
  66980. if (manager.numInfluencers > 0) {
  66981. defines.push("#define MORPHTARGETS");
  66982. morphInfluencers = manager.numInfluencers;
  66983. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66984. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66985. }
  66986. }
  66987. // Instances
  66988. if (useInstances) {
  66989. defines.push("#define INSTANCES");
  66990. attribs.push("world0");
  66991. attribs.push("world1");
  66992. attribs.push("world2");
  66993. attribs.push("world3");
  66994. }
  66995. // Get correct effect
  66996. var join = defines.join("\n");
  66997. if (this._cachedDefines !== join) {
  66998. this._cachedDefines = join;
  66999. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  67000. }
  67001. if (!this._effect.isReady()) {
  67002. return false;
  67003. }
  67004. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67005. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  67006. this._initializeBlurRTTAndPostProcesses();
  67007. }
  67008. }
  67009. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  67010. return false;
  67011. }
  67012. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  67013. return false;
  67014. }
  67015. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  67016. return false;
  67017. }
  67018. return true;
  67019. };
  67020. /**
  67021. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67022. * @param defines Defines of the material we want to update
  67023. * @param lightIndex Index of the light in the enabled light list of the material
  67024. */
  67025. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67026. var scene = this._scene;
  67027. var light = this._light;
  67028. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67029. return;
  67030. }
  67031. defines["SHADOW" + lightIndex] = true;
  67032. if (this.useContactHardeningShadow) {
  67033. defines["SHADOWPCSS" + lightIndex] = true;
  67034. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67035. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67036. }
  67037. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67038. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67039. }
  67040. // else default to high.
  67041. }
  67042. if (this.usePercentageCloserFiltering) {
  67043. defines["SHADOWPCF" + lightIndex] = true;
  67044. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67045. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67046. }
  67047. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67048. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67049. }
  67050. // else default to high.
  67051. }
  67052. else if (this.usePoissonSampling) {
  67053. defines["SHADOWPOISSON" + lightIndex] = true;
  67054. }
  67055. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67056. defines["SHADOWESM" + lightIndex] = true;
  67057. }
  67058. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67059. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67060. }
  67061. if (light.needCube()) {
  67062. defines["SHADOWCUBE" + lightIndex] = true;
  67063. }
  67064. };
  67065. /**
  67066. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67067. * defined in the generator but impacting the effect).
  67068. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67069. * @param effect The effect we are binfing the information for
  67070. */
  67071. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67072. var light = this._light;
  67073. var scene = this._scene;
  67074. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67075. return;
  67076. }
  67077. var camera = scene.activeCamera;
  67078. if (!camera) {
  67079. return;
  67080. }
  67081. var shadowMap = this.getShadowMap();
  67082. if (!shadowMap) {
  67083. return;
  67084. }
  67085. if (!light.needCube()) {
  67086. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67087. }
  67088. // Only PCF uses depth stencil texture.
  67089. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67090. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67091. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67092. }
  67093. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67094. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67095. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67096. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67097. }
  67098. else {
  67099. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67100. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67101. }
  67102. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67103. };
  67104. /**
  67105. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67106. * (eq to shadow prjection matrix * light transform matrix)
  67107. * @returns The transform matrix used to create the shadow map
  67108. */
  67109. ShadowGenerator.prototype.getTransformMatrix = function () {
  67110. var scene = this._scene;
  67111. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67112. return this._transformMatrix;
  67113. }
  67114. this._currentRenderID = scene.getRenderId();
  67115. this._currentFaceIndexCache = this._currentFaceIndex;
  67116. var lightPosition = this._light.position;
  67117. if (this._light.computeTransformedInformation()) {
  67118. lightPosition = this._light.transformedPosition;
  67119. }
  67120. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67121. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67122. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67123. }
  67124. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67125. this._cachedPosition.copyFrom(lightPosition);
  67126. this._cachedDirection.copyFrom(this._lightDirection);
  67127. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67128. var shadowMap = this.getShadowMap();
  67129. if (shadowMap) {
  67130. var renderList = shadowMap.renderList;
  67131. if (renderList) {
  67132. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67133. }
  67134. }
  67135. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67136. }
  67137. return this._transformMatrix;
  67138. };
  67139. /**
  67140. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67141. * Cube and 2D textures for instance.
  67142. */
  67143. ShadowGenerator.prototype.recreateShadowMap = function () {
  67144. var shadowMap = this._shadowMap;
  67145. if (!shadowMap) {
  67146. return;
  67147. }
  67148. // Track render list.
  67149. var renderList = shadowMap.renderList;
  67150. // Clean up existing data.
  67151. this._disposeRTTandPostProcesses();
  67152. // Reinitializes.
  67153. this._initializeGenerator();
  67154. // Reaffect the filter to ensure a correct fallback if necessary.
  67155. this.filter = this.filter;
  67156. // Reaffect the filter.
  67157. this._applyFilterValues();
  67158. // Reaffect Render List.
  67159. this._shadowMap.renderList = renderList;
  67160. };
  67161. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67162. if (this._shadowMap2) {
  67163. this._shadowMap2.dispose();
  67164. this._shadowMap2 = null;
  67165. }
  67166. if (this._boxBlurPostprocess) {
  67167. this._boxBlurPostprocess.dispose();
  67168. this._boxBlurPostprocess = null;
  67169. }
  67170. if (this._kernelBlurXPostprocess) {
  67171. this._kernelBlurXPostprocess.dispose();
  67172. this._kernelBlurXPostprocess = null;
  67173. }
  67174. if (this._kernelBlurYPostprocess) {
  67175. this._kernelBlurYPostprocess.dispose();
  67176. this._kernelBlurYPostprocess = null;
  67177. }
  67178. this._blurPostProcesses = [];
  67179. };
  67180. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67181. if (this._shadowMap) {
  67182. this._shadowMap.dispose();
  67183. this._shadowMap = null;
  67184. }
  67185. this._disposeBlurPostProcesses();
  67186. };
  67187. /**
  67188. * Disposes the ShadowGenerator.
  67189. * Returns nothing.
  67190. */
  67191. ShadowGenerator.prototype.dispose = function () {
  67192. this._disposeRTTandPostProcesses();
  67193. if (this._light) {
  67194. this._light._shadowGenerator = null;
  67195. this._light._markMeshesAsLightDirty();
  67196. }
  67197. };
  67198. /**
  67199. * Serializes the shadow generator setup to a json object.
  67200. * @returns The serialized JSON object
  67201. */
  67202. ShadowGenerator.prototype.serialize = function () {
  67203. var serializationObject = {};
  67204. var shadowMap = this.getShadowMap();
  67205. if (!shadowMap) {
  67206. return serializationObject;
  67207. }
  67208. serializationObject.lightId = this._light.id;
  67209. serializationObject.mapSize = shadowMap.getRenderSize();
  67210. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67211. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67212. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67213. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67214. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67215. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67216. serializationObject.depthScale = this.depthScale;
  67217. serializationObject.darkness = this.getDarkness();
  67218. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67219. serializationObject.blurKernel = this.blurKernel;
  67220. serializationObject.blurScale = this.blurScale;
  67221. serializationObject.useKernelBlur = this.useKernelBlur;
  67222. serializationObject.transparencyShadow = this._transparencyShadow;
  67223. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67224. serializationObject.bias = this.bias;
  67225. serializationObject.normalBias = this.normalBias;
  67226. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67227. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67228. serializationObject.filteringQuality = this.filteringQuality;
  67229. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67230. serializationObject.renderList = [];
  67231. if (shadowMap.renderList) {
  67232. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67233. var mesh = shadowMap.renderList[meshIndex];
  67234. serializationObject.renderList.push(mesh.id);
  67235. }
  67236. }
  67237. return serializationObject;
  67238. };
  67239. /**
  67240. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67241. * @param parsedShadowGenerator The JSON object to parse
  67242. * @param scene The scene to create the shadow map for
  67243. * @returns The parsed shadow generator
  67244. */
  67245. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67246. //casting to point light, as light is missing the position attr and typescript complains.
  67247. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67248. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67249. var shadowMap = shadowGenerator.getShadowMap();
  67250. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67251. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67252. meshes.forEach(function (mesh) {
  67253. if (!shadowMap) {
  67254. return;
  67255. }
  67256. if (!shadowMap.renderList) {
  67257. shadowMap.renderList = [];
  67258. }
  67259. shadowMap.renderList.push(mesh);
  67260. });
  67261. }
  67262. if (parsedShadowGenerator.usePoissonSampling) {
  67263. shadowGenerator.usePoissonSampling = true;
  67264. }
  67265. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67266. shadowGenerator.useExponentialShadowMap = true;
  67267. }
  67268. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67269. shadowGenerator.useBlurExponentialShadowMap = true;
  67270. }
  67271. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67272. shadowGenerator.useCloseExponentialShadowMap = true;
  67273. }
  67274. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67275. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67276. }
  67277. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67278. shadowGenerator.usePercentageCloserFiltering = true;
  67279. }
  67280. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67281. shadowGenerator.useContactHardeningShadow = true;
  67282. }
  67283. if (parsedShadowGenerator.filteringQuality) {
  67284. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67285. }
  67286. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67287. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67288. }
  67289. // Backward compat
  67290. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67291. shadowGenerator.useExponentialShadowMap = true;
  67292. }
  67293. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67294. shadowGenerator.useBlurExponentialShadowMap = true;
  67295. }
  67296. if (parsedShadowGenerator.depthScale) {
  67297. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67298. }
  67299. if (parsedShadowGenerator.blurScale) {
  67300. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67301. }
  67302. if (parsedShadowGenerator.blurBoxOffset) {
  67303. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67304. }
  67305. if (parsedShadowGenerator.useKernelBlur) {
  67306. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67307. }
  67308. if (parsedShadowGenerator.blurKernel) {
  67309. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67310. }
  67311. if (parsedShadowGenerator.bias !== undefined) {
  67312. shadowGenerator.bias = parsedShadowGenerator.bias;
  67313. }
  67314. if (parsedShadowGenerator.normalBias !== undefined) {
  67315. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67316. }
  67317. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67318. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67319. }
  67320. if (parsedShadowGenerator.darkness) {
  67321. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67322. }
  67323. if (parsedShadowGenerator.transparencyShadow) {
  67324. shadowGenerator.setTransparencyShadow(true);
  67325. }
  67326. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67327. return shadowGenerator;
  67328. };
  67329. /**
  67330. * Shadow generator mode None: no filtering applied.
  67331. */
  67332. ShadowGenerator.FILTER_NONE = 0;
  67333. /**
  67334. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67335. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67336. */
  67337. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67338. /**
  67339. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67340. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67341. */
  67342. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67343. /**
  67344. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67345. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67346. */
  67347. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67348. /**
  67349. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67350. * edge artifacts on steep falloff.
  67351. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67352. */
  67353. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67354. /**
  67355. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67356. * edge artifacts on steep falloff.
  67357. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67358. */
  67359. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67360. /**
  67361. * Shadow generator mode PCF: Percentage Closer Filtering
  67362. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67363. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67364. */
  67365. ShadowGenerator.FILTER_PCF = 6;
  67366. /**
  67367. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67368. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67369. * Contact Hardening
  67370. */
  67371. ShadowGenerator.FILTER_PCSS = 7;
  67372. /**
  67373. * Reserved for PCF and PCSS
  67374. * Highest Quality.
  67375. *
  67376. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67377. *
  67378. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67379. */
  67380. ShadowGenerator.QUALITY_HIGH = 0;
  67381. /**
  67382. * Reserved for PCF and PCSS
  67383. * Good tradeoff for quality/perf cross devices
  67384. *
  67385. * Execute PCF on a 3*3 kernel.
  67386. *
  67387. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67388. */
  67389. ShadowGenerator.QUALITY_MEDIUM = 1;
  67390. /**
  67391. * Reserved for PCF and PCSS
  67392. * The lowest quality but the fastest.
  67393. *
  67394. * Execute PCF on a 1*1 kernel.
  67395. *
  67396. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67397. */
  67398. ShadowGenerator.QUALITY_LOW = 2;
  67399. return ShadowGenerator;
  67400. }());
  67401. BABYLON.ShadowGenerator = ShadowGenerator;
  67402. })(BABYLON || (BABYLON = {}));
  67403. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67404. var BABYLON;
  67405. (function (BABYLON) {
  67406. var DefaultLoadingScreen = /** @class */ (function () {
  67407. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67408. if (_loadingText === void 0) { _loadingText = ""; }
  67409. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67410. var _this = this;
  67411. this._renderingCanvas = _renderingCanvas;
  67412. this._loadingText = _loadingText;
  67413. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67414. // Resize
  67415. this._resizeLoadingUI = function () {
  67416. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67417. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67418. if (!_this._loadingDiv) {
  67419. return;
  67420. }
  67421. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67422. _this._loadingDiv.style.left = canvasRect.left + "px";
  67423. _this._loadingDiv.style.top = canvasRect.top + "px";
  67424. _this._loadingDiv.style.width = canvasRect.width + "px";
  67425. _this._loadingDiv.style.height = canvasRect.height + "px";
  67426. };
  67427. }
  67428. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67429. if (this._loadingDiv) {
  67430. // Do not add a loading screen if there is already one
  67431. return;
  67432. }
  67433. this._loadingDiv = document.createElement("div");
  67434. this._loadingDiv.id = "babylonjsLoadingDiv";
  67435. this._loadingDiv.style.opacity = "0";
  67436. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67437. this._loadingDiv.style.pointerEvents = "none";
  67438. // Loading text
  67439. this._loadingTextDiv = document.createElement("div");
  67440. this._loadingTextDiv.style.position = "absolute";
  67441. this._loadingTextDiv.style.left = "0";
  67442. this._loadingTextDiv.style.top = "50%";
  67443. this._loadingTextDiv.style.marginTop = "80px";
  67444. this._loadingTextDiv.style.width = "100%";
  67445. this._loadingTextDiv.style.height = "20px";
  67446. this._loadingTextDiv.style.fontFamily = "Arial";
  67447. this._loadingTextDiv.style.fontSize = "14px";
  67448. this._loadingTextDiv.style.color = "white";
  67449. this._loadingTextDiv.style.textAlign = "center";
  67450. this._loadingTextDiv.innerHTML = "Loading";
  67451. this._loadingDiv.appendChild(this._loadingTextDiv);
  67452. //set the predefined text
  67453. this._loadingTextDiv.innerHTML = this._loadingText;
  67454. // Generating keyframes
  67455. var style = document.createElement('style');
  67456. style.type = 'text/css';
  67457. 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 }";
  67458. style.innerHTML = keyFrames;
  67459. document.getElementsByTagName('head')[0].appendChild(style);
  67460. // Loading img
  67461. var imgBack = new Image();
  67462. 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";
  67463. imgBack.style.position = "absolute";
  67464. imgBack.style.left = "50%";
  67465. imgBack.style.top = "50%";
  67466. imgBack.style.marginLeft = "-60px";
  67467. imgBack.style.marginTop = "-60px";
  67468. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67469. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67470. imgBack.style.transformOrigin = "50% 50%";
  67471. imgBack.style.webkitTransformOrigin = "50% 50%";
  67472. this._loadingDiv.appendChild(imgBack);
  67473. this._resizeLoadingUI();
  67474. window.addEventListener("resize", this._resizeLoadingUI);
  67475. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67476. document.body.appendChild(this._loadingDiv);
  67477. this._loadingDiv.style.opacity = "1";
  67478. };
  67479. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67480. var _this = this;
  67481. if (!this._loadingDiv) {
  67482. return;
  67483. }
  67484. var onTransitionEnd = function () {
  67485. if (!_this._loadingDiv) {
  67486. return;
  67487. }
  67488. document.body.removeChild(_this._loadingDiv);
  67489. window.removeEventListener("resize", _this._resizeLoadingUI);
  67490. _this._loadingDiv = null;
  67491. };
  67492. this._loadingDiv.style.opacity = "0";
  67493. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67494. };
  67495. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67496. set: function (text) {
  67497. this._loadingText = text;
  67498. if (this._loadingTextDiv) {
  67499. this._loadingTextDiv.innerHTML = this._loadingText;
  67500. }
  67501. },
  67502. enumerable: true,
  67503. configurable: true
  67504. });
  67505. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67506. get: function () {
  67507. return this._loadingDivBackgroundColor;
  67508. },
  67509. set: function (color) {
  67510. this._loadingDivBackgroundColor = color;
  67511. if (!this._loadingDiv) {
  67512. return;
  67513. }
  67514. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67515. },
  67516. enumerable: true,
  67517. configurable: true
  67518. });
  67519. return DefaultLoadingScreen;
  67520. }());
  67521. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67522. })(BABYLON || (BABYLON = {}));
  67523. //# sourceMappingURL=babylon.loadingScreen.js.map
  67524. var BABYLON;
  67525. (function (BABYLON) {
  67526. var SceneLoaderProgressEvent = /** @class */ (function () {
  67527. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67528. this.lengthComputable = lengthComputable;
  67529. this.loaded = loaded;
  67530. this.total = total;
  67531. }
  67532. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67533. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67534. };
  67535. return SceneLoaderProgressEvent;
  67536. }());
  67537. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67538. var SceneLoader = /** @class */ (function () {
  67539. function SceneLoader() {
  67540. }
  67541. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67542. get: function () {
  67543. return 0;
  67544. },
  67545. enumerable: true,
  67546. configurable: true
  67547. });
  67548. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67549. get: function () {
  67550. return 1;
  67551. },
  67552. enumerable: true,
  67553. configurable: true
  67554. });
  67555. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67556. get: function () {
  67557. return 2;
  67558. },
  67559. enumerable: true,
  67560. configurable: true
  67561. });
  67562. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67563. get: function () {
  67564. return 3;
  67565. },
  67566. enumerable: true,
  67567. configurable: true
  67568. });
  67569. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67570. get: function () {
  67571. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67572. },
  67573. set: function (value) {
  67574. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67575. },
  67576. enumerable: true,
  67577. configurable: true
  67578. });
  67579. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67580. get: function () {
  67581. return SceneLoader._ShowLoadingScreen;
  67582. },
  67583. set: function (value) {
  67584. SceneLoader._ShowLoadingScreen = value;
  67585. },
  67586. enumerable: true,
  67587. configurable: true
  67588. });
  67589. Object.defineProperty(SceneLoader, "loggingLevel", {
  67590. get: function () {
  67591. return SceneLoader._loggingLevel;
  67592. },
  67593. set: function (value) {
  67594. SceneLoader._loggingLevel = value;
  67595. },
  67596. enumerable: true,
  67597. configurable: true
  67598. });
  67599. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67600. get: function () {
  67601. return SceneLoader._CleanBoneMatrixWeights;
  67602. },
  67603. set: function (value) {
  67604. SceneLoader._CleanBoneMatrixWeights = value;
  67605. },
  67606. enumerable: true,
  67607. configurable: true
  67608. });
  67609. SceneLoader._getDefaultPlugin = function () {
  67610. return SceneLoader._registeredPlugins[".babylon"];
  67611. };
  67612. SceneLoader._getPluginForExtension = function (extension) {
  67613. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67614. if (registeredPlugin) {
  67615. return registeredPlugin;
  67616. }
  67617. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67618. return SceneLoader._getDefaultPlugin();
  67619. };
  67620. SceneLoader._getPluginForDirectLoad = function (data) {
  67621. for (var extension in SceneLoader._registeredPlugins) {
  67622. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67623. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67624. return SceneLoader._registeredPlugins[extension];
  67625. }
  67626. }
  67627. return SceneLoader._getDefaultPlugin();
  67628. };
  67629. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67630. if (sceneFilename.name) {
  67631. sceneFilename = sceneFilename.name;
  67632. }
  67633. var queryStringPosition = sceneFilename.indexOf("?");
  67634. if (queryStringPosition !== -1) {
  67635. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67636. }
  67637. var dotPosition = sceneFilename.lastIndexOf(".");
  67638. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67639. return SceneLoader._getPluginForExtension(extension);
  67640. };
  67641. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67642. SceneLoader._getDirectLoad = function (sceneFilename) {
  67643. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67644. return sceneFilename.substr(5);
  67645. }
  67646. return null;
  67647. };
  67648. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67649. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67650. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67651. var plugin;
  67652. if (registeredPlugin.plugin.createPlugin) {
  67653. plugin = registeredPlugin.plugin.createPlugin();
  67654. }
  67655. else {
  67656. plugin = registeredPlugin.plugin;
  67657. }
  67658. var useArrayBuffer = registeredPlugin.isBinary;
  67659. var database;
  67660. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67661. var dataCallback = function (data, responseURL) {
  67662. if (scene.isDisposed) {
  67663. onError("Scene has been disposed");
  67664. return;
  67665. }
  67666. scene.database = database;
  67667. onSuccess(plugin, data, responseURL);
  67668. };
  67669. var request = null;
  67670. var pluginDisposed = false;
  67671. var onDisposeObservable = plugin.onDisposeObservable;
  67672. if (onDisposeObservable) {
  67673. onDisposeObservable.add(function () {
  67674. pluginDisposed = true;
  67675. if (request) {
  67676. request.abort();
  67677. request = null;
  67678. }
  67679. onDispose();
  67680. });
  67681. }
  67682. var manifestChecked = function () {
  67683. if (pluginDisposed) {
  67684. return;
  67685. }
  67686. var url = rootUrl + sceneFilename;
  67687. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67688. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67689. } : undefined, database, useArrayBuffer, function (request, exception) {
  67690. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67691. });
  67692. };
  67693. if (directLoad) {
  67694. dataCallback(directLoad);
  67695. return plugin;
  67696. }
  67697. if (rootUrl.indexOf("file:") === -1) {
  67698. var engine = scene.getEngine();
  67699. var canUseOfflineSupport = engine.enableOfflineSupport;
  67700. if (canUseOfflineSupport) {
  67701. // Also check for exceptions
  67702. var exceptionFound = false;
  67703. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67704. var regex = _a[_i];
  67705. if (regex.test(rootUrl + sceneFilename)) {
  67706. exceptionFound = true;
  67707. break;
  67708. }
  67709. }
  67710. canUseOfflineSupport = !exceptionFound;
  67711. }
  67712. if (canUseOfflineSupport) {
  67713. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67714. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67715. }
  67716. else {
  67717. manifestChecked();
  67718. }
  67719. }
  67720. // Loading file from disk via input file or drag'n'drop
  67721. else {
  67722. var fileOrString = sceneFilename;
  67723. if (fileOrString.name) { // File
  67724. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67725. }
  67726. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67727. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67728. }
  67729. else {
  67730. onError("Unable to find file named " + sceneFilename);
  67731. }
  67732. }
  67733. return plugin;
  67734. };
  67735. // Public functions
  67736. SceneLoader.GetPluginForExtension = function (extension) {
  67737. return SceneLoader._getPluginForExtension(extension).plugin;
  67738. };
  67739. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67740. return !!SceneLoader._registeredPlugins[extension];
  67741. };
  67742. SceneLoader.RegisterPlugin = function (plugin) {
  67743. if (typeof plugin.extensions === "string") {
  67744. var extension = plugin.extensions;
  67745. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67746. plugin: plugin,
  67747. isBinary: false
  67748. };
  67749. }
  67750. else {
  67751. var extensions = plugin.extensions;
  67752. Object.keys(extensions).forEach(function (extension) {
  67753. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67754. plugin: plugin,
  67755. isBinary: extensions[extension].isBinary
  67756. };
  67757. });
  67758. }
  67759. };
  67760. /**
  67761. * Import meshes into a scene
  67762. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67763. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67764. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67765. * @param scene the instance of BABYLON.Scene to append to
  67766. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67767. * @param onProgress a callback with a progress event for each file being loaded
  67768. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67769. * @param pluginExtension the extension used to determine the plugin
  67770. * @returns The loaded plugin
  67771. */
  67772. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67773. if (sceneFilename === void 0) { sceneFilename = ""; }
  67774. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67775. if (onSuccess === void 0) { onSuccess = null; }
  67776. if (onProgress === void 0) { onProgress = null; }
  67777. if (onError === void 0) { onError = null; }
  67778. if (pluginExtension === void 0) { pluginExtension = null; }
  67779. if (!scene) {
  67780. BABYLON.Tools.Error("No scene available to import mesh to");
  67781. return null;
  67782. }
  67783. if (!sceneFilename) {
  67784. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67785. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67786. }
  67787. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67788. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67789. return null;
  67790. }
  67791. var loadingToken = {};
  67792. scene._addPendingData(loadingToken);
  67793. var disposeHandler = function () {
  67794. scene._removePendingData(loadingToken);
  67795. };
  67796. var errorHandler = function (message, exception) {
  67797. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67798. if (onError) {
  67799. onError(scene, errorMessage, exception);
  67800. }
  67801. else {
  67802. BABYLON.Tools.Error(errorMessage);
  67803. // should the exception be thrown?
  67804. }
  67805. disposeHandler();
  67806. };
  67807. var progressHandler = onProgress ? function (event) {
  67808. try {
  67809. onProgress(event);
  67810. }
  67811. catch (e) {
  67812. errorHandler("Error in onProgress callback", e);
  67813. }
  67814. } : undefined;
  67815. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67816. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67817. if (onSuccess) {
  67818. try {
  67819. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67820. }
  67821. catch (e) {
  67822. errorHandler("Error in onSuccess callback", e);
  67823. }
  67824. }
  67825. scene._removePendingData(loadingToken);
  67826. };
  67827. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67828. if (plugin.rewriteRootURL) {
  67829. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67830. }
  67831. if (sceneFilename === "") {
  67832. if (sceneFilename === "") {
  67833. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67834. }
  67835. }
  67836. if (plugin.importMesh) {
  67837. var syncedPlugin = plugin;
  67838. var meshes = new Array();
  67839. var particleSystems = new Array();
  67840. var skeletons = new Array();
  67841. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67842. return;
  67843. }
  67844. scene.loadingPluginName = plugin.name;
  67845. successHandler(meshes, particleSystems, skeletons, []);
  67846. }
  67847. else {
  67848. var asyncedPlugin = plugin;
  67849. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67850. scene.loadingPluginName = plugin.name;
  67851. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67852. }).catch(function (error) {
  67853. errorHandler(error.message, error);
  67854. });
  67855. }
  67856. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67857. };
  67858. /**
  67859. * Import meshes into a scene
  67860. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67861. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67862. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67863. * @param scene the instance of BABYLON.Scene to append to
  67864. * @param onProgress a callback with a progress event for each file being loaded
  67865. * @param pluginExtension the extension used to determine the plugin
  67866. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67867. */
  67868. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67869. if (sceneFilename === void 0) { sceneFilename = ""; }
  67870. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67871. if (onProgress === void 0) { onProgress = null; }
  67872. if (pluginExtension === void 0) { pluginExtension = null; }
  67873. return new Promise(function (resolve, reject) {
  67874. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67875. resolve({
  67876. meshes: meshes,
  67877. particleSystems: particleSystems,
  67878. skeletons: skeletons,
  67879. animationGroups: animationGroups
  67880. });
  67881. }, onProgress, function (scene, message, exception) {
  67882. reject(exception || new Error(message));
  67883. }, pluginExtension);
  67884. });
  67885. };
  67886. /**
  67887. * Load a scene
  67888. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67889. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67890. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67891. * @param onSuccess a callback with the scene when import succeeds
  67892. * @param onProgress a callback with a progress event for each file being loaded
  67893. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67894. * @param pluginExtension the extension used to determine the plugin
  67895. * @returns The loaded plugin
  67896. */
  67897. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67898. if (onSuccess === void 0) { onSuccess = null; }
  67899. if (onProgress === void 0) { onProgress = null; }
  67900. if (onError === void 0) { onError = null; }
  67901. if (pluginExtension === void 0) { pluginExtension = null; }
  67902. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67903. };
  67904. /**
  67905. * Load a scene
  67906. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67907. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67908. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67909. * @param onProgress a callback with a progress event for each file being loaded
  67910. * @param pluginExtension the extension used to determine the plugin
  67911. * @returns The loaded scene
  67912. */
  67913. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67914. if (onProgress === void 0) { onProgress = null; }
  67915. if (pluginExtension === void 0) { pluginExtension = null; }
  67916. return new Promise(function (resolve, reject) {
  67917. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67918. resolve(scene);
  67919. }, onProgress, function (scene, message, exception) {
  67920. reject(exception || new Error(message));
  67921. }, pluginExtension);
  67922. });
  67923. };
  67924. /**
  67925. * Append a scene
  67926. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67927. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67928. * @param scene is the instance of BABYLON.Scene to append to
  67929. * @param onSuccess a callback with the scene when import succeeds
  67930. * @param onProgress a callback with a progress event for each file being loaded
  67931. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67932. * @param pluginExtension the extension used to determine the plugin
  67933. * @returns The loaded plugin
  67934. */
  67935. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67936. if (sceneFilename === void 0) { sceneFilename = ""; }
  67937. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67938. if (onSuccess === void 0) { onSuccess = null; }
  67939. if (onProgress === void 0) { onProgress = null; }
  67940. if (onError === void 0) { onError = null; }
  67941. if (pluginExtension === void 0) { pluginExtension = null; }
  67942. if (!scene) {
  67943. BABYLON.Tools.Error("No scene available to append to");
  67944. return null;
  67945. }
  67946. if (!sceneFilename) {
  67947. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67948. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67949. }
  67950. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67951. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67952. return null;
  67953. }
  67954. if (SceneLoader.ShowLoadingScreen) {
  67955. scene.getEngine().displayLoadingUI();
  67956. }
  67957. var loadingToken = {};
  67958. scene._addPendingData(loadingToken);
  67959. var disposeHandler = function () {
  67960. scene._removePendingData(loadingToken);
  67961. scene.getEngine().hideLoadingUI();
  67962. };
  67963. var errorHandler = function (message, exception) {
  67964. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67965. if (onError) {
  67966. onError(scene, errorMessage, exception);
  67967. }
  67968. else {
  67969. BABYLON.Tools.Error(errorMessage);
  67970. // should the exception be thrown?
  67971. }
  67972. disposeHandler();
  67973. };
  67974. var progressHandler = onProgress ? function (event) {
  67975. try {
  67976. onProgress(event);
  67977. }
  67978. catch (e) {
  67979. errorHandler("Error in onProgress callback", e);
  67980. }
  67981. } : undefined;
  67982. var successHandler = function () {
  67983. if (onSuccess) {
  67984. try {
  67985. onSuccess(scene);
  67986. }
  67987. catch (e) {
  67988. errorHandler("Error in onSuccess callback", e);
  67989. }
  67990. }
  67991. scene._removePendingData(loadingToken);
  67992. };
  67993. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67994. if (sceneFilename === "") {
  67995. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67996. }
  67997. if (plugin.load) {
  67998. var syncedPlugin = plugin;
  67999. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  68000. return;
  68001. }
  68002. scene.loadingPluginName = plugin.name;
  68003. successHandler();
  68004. }
  68005. else {
  68006. var asyncedPlugin = plugin;
  68007. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  68008. scene.loadingPluginName = plugin.name;
  68009. successHandler();
  68010. }).catch(function (error) {
  68011. errorHandler(error.message, error);
  68012. });
  68013. }
  68014. if (SceneLoader.ShowLoadingScreen) {
  68015. scene.executeWhenReady(function () {
  68016. scene.getEngine().hideLoadingUI();
  68017. });
  68018. }
  68019. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68020. };
  68021. /**
  68022. * Append a scene
  68023. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68024. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68025. * @param scene is the instance of BABYLON.Scene to append to
  68026. * @param onProgress a callback with a progress event for each file being loaded
  68027. * @param pluginExtension the extension used to determine the plugin
  68028. * @returns The given scene
  68029. */
  68030. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68031. if (sceneFilename === void 0) { sceneFilename = ""; }
  68032. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68033. if (onProgress === void 0) { onProgress = null; }
  68034. if (pluginExtension === void 0) { pluginExtension = null; }
  68035. return new Promise(function (resolve, reject) {
  68036. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68037. resolve(scene);
  68038. }, onProgress, function (scene, message, exception) {
  68039. reject(exception || new Error(message));
  68040. }, pluginExtension);
  68041. });
  68042. };
  68043. /**
  68044. * Load a scene into an asset container
  68045. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68046. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68047. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68048. * @param onSuccess a callback with the scene when import succeeds
  68049. * @param onProgress a callback with a progress event for each file being loaded
  68050. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68051. * @param pluginExtension the extension used to determine the plugin
  68052. * @returns The loaded plugin
  68053. */
  68054. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68055. if (sceneFilename === void 0) { sceneFilename = ""; }
  68056. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68057. if (onSuccess === void 0) { onSuccess = null; }
  68058. if (onProgress === void 0) { onProgress = null; }
  68059. if (onError === void 0) { onError = null; }
  68060. if (pluginExtension === void 0) { pluginExtension = null; }
  68061. if (!scene) {
  68062. BABYLON.Tools.Error("No scene available to load asset container to");
  68063. return null;
  68064. }
  68065. if (!sceneFilename) {
  68066. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68067. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68068. }
  68069. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68070. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68071. return null;
  68072. }
  68073. var loadingToken = {};
  68074. scene._addPendingData(loadingToken);
  68075. var disposeHandler = function () {
  68076. scene._removePendingData(loadingToken);
  68077. };
  68078. var errorHandler = function (message, exception) {
  68079. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68080. if (onError) {
  68081. onError(scene, errorMessage, exception);
  68082. }
  68083. else {
  68084. BABYLON.Tools.Error(errorMessage);
  68085. // should the exception be thrown?
  68086. }
  68087. disposeHandler();
  68088. };
  68089. var progressHandler = onProgress ? function (event) {
  68090. try {
  68091. onProgress(event);
  68092. }
  68093. catch (e) {
  68094. errorHandler("Error in onProgress callback", e);
  68095. }
  68096. } : undefined;
  68097. var successHandler = function (assets) {
  68098. if (onSuccess) {
  68099. try {
  68100. onSuccess(assets);
  68101. }
  68102. catch (e) {
  68103. errorHandler("Error in onSuccess callback", e);
  68104. }
  68105. }
  68106. scene._removePendingData(loadingToken);
  68107. };
  68108. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68109. if (plugin.loadAssetContainer) {
  68110. var syncedPlugin = plugin;
  68111. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68112. if (!assetContainer) {
  68113. return;
  68114. }
  68115. scene.loadingPluginName = plugin.name;
  68116. successHandler(assetContainer);
  68117. }
  68118. else if (plugin.loadAssetContainerAsync) {
  68119. var asyncedPlugin = plugin;
  68120. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68121. scene.loadingPluginName = plugin.name;
  68122. successHandler(assetContainer);
  68123. }).catch(function (error) {
  68124. errorHandler(error.message, error);
  68125. });
  68126. }
  68127. else {
  68128. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68129. }
  68130. if (SceneLoader.ShowLoadingScreen) {
  68131. scene.executeWhenReady(function () {
  68132. scene.getEngine().hideLoadingUI();
  68133. });
  68134. }
  68135. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68136. };
  68137. /**
  68138. * Load a scene into an asset container
  68139. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68140. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68141. * @param scene is the instance of BABYLON.Scene to append to
  68142. * @param onProgress a callback with a progress event for each file being loaded
  68143. * @param pluginExtension the extension used to determine the plugin
  68144. * @returns The loaded asset container
  68145. */
  68146. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68147. if (sceneFilename === void 0) { sceneFilename = ""; }
  68148. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68149. if (onProgress === void 0) { onProgress = null; }
  68150. if (pluginExtension === void 0) { pluginExtension = null; }
  68151. return new Promise(function (resolve, reject) {
  68152. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68153. resolve(assetContainer);
  68154. }, onProgress, function (scene, message, exception) {
  68155. reject(exception || new Error(message));
  68156. }, pluginExtension);
  68157. });
  68158. };
  68159. // Flags
  68160. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68161. SceneLoader._ShowLoadingScreen = true;
  68162. SceneLoader._CleanBoneMatrixWeights = false;
  68163. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68164. // Members
  68165. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68166. SceneLoader._registeredPlugins = {};
  68167. return SceneLoader;
  68168. }());
  68169. BABYLON.SceneLoader = SceneLoader;
  68170. ;
  68171. })(BABYLON || (BABYLON = {}));
  68172. //# sourceMappingURL=babylon.sceneLoader.js.map
  68173. var BABYLON;
  68174. (function (BABYLON) {
  68175. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68176. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68177. var parsedMaterial = parsedData.materials[index];
  68178. if (parsedMaterial.id === id) {
  68179. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68180. }
  68181. }
  68182. return null;
  68183. };
  68184. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68185. for (var i in names) {
  68186. if (mesh.name === names[i]) {
  68187. hierarchyIds.push(mesh.id);
  68188. return true;
  68189. }
  68190. }
  68191. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68192. hierarchyIds.push(mesh.id);
  68193. return true;
  68194. }
  68195. return false;
  68196. };
  68197. var logOperation = function (operation, producer) {
  68198. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68199. };
  68200. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68201. if (addToScene === void 0) { addToScene = false; }
  68202. var container = new BABYLON.AssetContainer(scene);
  68203. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68204. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68205. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68206. // and avoid problems with multiple concurrent .babylon loads.
  68207. var log = "importScene has failed JSON parse";
  68208. try {
  68209. var parsedData = JSON.parse(data);
  68210. log = "";
  68211. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68212. var index;
  68213. var cache;
  68214. // Lights
  68215. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68216. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68217. var parsedLight = parsedData.lights[index];
  68218. var light = BABYLON.Light.Parse(parsedLight, scene);
  68219. if (light) {
  68220. container.lights.push(light);
  68221. log += (index === 0 ? "\n\tLights:" : "");
  68222. log += "\n\t\t" + light.toString(fullDetails);
  68223. }
  68224. }
  68225. }
  68226. // Animations
  68227. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68228. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68229. var parsedAnimation = parsedData.animations[index];
  68230. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68231. scene.animations.push(animation);
  68232. container.animations.push(animation);
  68233. log += (index === 0 ? "\n\tAnimations:" : "");
  68234. log += "\n\t\t" + animation.toString(fullDetails);
  68235. }
  68236. }
  68237. // Materials
  68238. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68239. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68240. var parsedMaterial = parsedData.materials[index];
  68241. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68242. container.materials.push(mat);
  68243. log += (index === 0 ? "\n\tMaterials:" : "");
  68244. log += "\n\t\t" + mat.toString(fullDetails);
  68245. }
  68246. }
  68247. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68248. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68249. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68250. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68251. container.multiMaterials.push(mmat);
  68252. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68253. log += "\n\t\t" + mmat.toString(fullDetails);
  68254. }
  68255. }
  68256. // Morph targets
  68257. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68258. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68259. var managerData = _a[_i];
  68260. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68261. }
  68262. }
  68263. // Skeletons
  68264. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68265. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68266. var parsedSkeleton = parsedData.skeletons[index];
  68267. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68268. container.skeletons.push(skeleton);
  68269. log += (index === 0 ? "\n\tSkeletons:" : "");
  68270. log += "\n\t\t" + skeleton.toString(fullDetails);
  68271. }
  68272. }
  68273. // Geometries
  68274. var geometries = parsedData.geometries;
  68275. if (geometries !== undefined && geometries !== null) {
  68276. var addedGeometry = new Array();
  68277. // Boxes
  68278. var boxes = geometries.boxes;
  68279. if (boxes !== undefined && boxes !== null) {
  68280. for (index = 0, cache = boxes.length; index < cache; index++) {
  68281. var parsedBox = boxes[index];
  68282. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68283. }
  68284. }
  68285. // Spheres
  68286. var spheres = geometries.spheres;
  68287. if (spheres !== undefined && spheres !== null) {
  68288. for (index = 0, cache = spheres.length; index < cache; index++) {
  68289. var parsedSphere = spheres[index];
  68290. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68291. }
  68292. }
  68293. // Cylinders
  68294. var cylinders = geometries.cylinders;
  68295. if (cylinders !== undefined && cylinders !== null) {
  68296. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68297. var parsedCylinder = cylinders[index];
  68298. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68299. }
  68300. }
  68301. // Toruses
  68302. var toruses = geometries.toruses;
  68303. if (toruses !== undefined && toruses !== null) {
  68304. for (index = 0, cache = toruses.length; index < cache; index++) {
  68305. var parsedTorus = toruses[index];
  68306. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68307. }
  68308. }
  68309. // Grounds
  68310. var grounds = geometries.grounds;
  68311. if (grounds !== undefined && grounds !== null) {
  68312. for (index = 0, cache = grounds.length; index < cache; index++) {
  68313. var parsedGround = grounds[index];
  68314. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68315. }
  68316. }
  68317. // Planes
  68318. var planes = geometries.planes;
  68319. if (planes !== undefined && planes !== null) {
  68320. for (index = 0, cache = planes.length; index < cache; index++) {
  68321. var parsedPlane = planes[index];
  68322. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68323. }
  68324. }
  68325. // TorusKnots
  68326. var torusKnots = geometries.torusKnots;
  68327. if (torusKnots !== undefined && torusKnots !== null) {
  68328. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68329. var parsedTorusKnot = torusKnots[index];
  68330. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68331. }
  68332. }
  68333. // VertexData
  68334. var vertexData = geometries.vertexData;
  68335. if (vertexData !== undefined && vertexData !== null) {
  68336. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68337. var parsedVertexData = vertexData[index];
  68338. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68339. }
  68340. }
  68341. addedGeometry.forEach(function (g) {
  68342. if (g) {
  68343. container.geometries.push(g);
  68344. }
  68345. });
  68346. }
  68347. // Transform nodes
  68348. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68349. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68350. var parsedTransformNode = parsedData.transformNodes[index];
  68351. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68352. container.transformNodes.push(node);
  68353. }
  68354. }
  68355. // Meshes
  68356. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68357. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68358. var parsedMesh = parsedData.meshes[index];
  68359. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68360. container.meshes.push(mesh);
  68361. log += (index === 0 ? "\n\tMeshes:" : "");
  68362. log += "\n\t\t" + mesh.toString(fullDetails);
  68363. }
  68364. }
  68365. // Cameras
  68366. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68367. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68368. var parsedCamera = parsedData.cameras[index];
  68369. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68370. container.cameras.push(camera);
  68371. log += (index === 0 ? "\n\tCameras:" : "");
  68372. log += "\n\t\t" + camera.toString(fullDetails);
  68373. }
  68374. }
  68375. // Browsing all the graph to connect the dots
  68376. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68377. var camera = scene.cameras[index];
  68378. if (camera._waitingParentId) {
  68379. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68380. camera._waitingParentId = null;
  68381. }
  68382. }
  68383. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68384. var light_1 = scene.lights[index];
  68385. if (light_1 && light_1._waitingParentId) {
  68386. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68387. light_1._waitingParentId = null;
  68388. }
  68389. }
  68390. // Sounds
  68391. // TODO: add sound
  68392. var loadedSounds = [];
  68393. var loadedSound;
  68394. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68395. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68396. var parsedSound = parsedData.sounds[index];
  68397. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68398. if (!parsedSound.url)
  68399. parsedSound.url = parsedSound.name;
  68400. if (!loadedSounds[parsedSound.url]) {
  68401. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68402. loadedSounds[parsedSound.url] = loadedSound;
  68403. container.sounds.push(loadedSound);
  68404. }
  68405. else {
  68406. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68407. }
  68408. }
  68409. else {
  68410. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68411. }
  68412. }
  68413. }
  68414. loadedSounds = [];
  68415. // Connect parents & children and parse actions
  68416. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68417. var transformNode = scene.transformNodes[index];
  68418. if (transformNode._waitingParentId) {
  68419. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68420. transformNode._waitingParentId = null;
  68421. }
  68422. }
  68423. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68424. var mesh = scene.meshes[index];
  68425. if (mesh._waitingParentId) {
  68426. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68427. mesh._waitingParentId = null;
  68428. }
  68429. if (mesh._waitingActions) {
  68430. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68431. mesh._waitingActions = null;
  68432. }
  68433. }
  68434. // freeze world matrix application
  68435. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68436. var currentMesh = scene.meshes[index];
  68437. if (currentMesh._waitingFreezeWorldMatrix) {
  68438. currentMesh.freezeWorldMatrix();
  68439. currentMesh._waitingFreezeWorldMatrix = null;
  68440. }
  68441. else {
  68442. currentMesh.computeWorldMatrix(true);
  68443. }
  68444. }
  68445. // Particles Systems
  68446. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68447. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68448. var parsedParticleSystem = parsedData.particleSystems[index];
  68449. if (parsedParticleSystem.activeParticleCount) {
  68450. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68451. container.particleSystems.push(ps);
  68452. }
  68453. else {
  68454. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68455. container.particleSystems.push(ps);
  68456. }
  68457. }
  68458. }
  68459. // Lens flares
  68460. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68461. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68462. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68463. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68464. container.lensFlareSystems.push(lf);
  68465. }
  68466. }
  68467. // Shadows
  68468. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68469. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68470. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68471. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68472. container.shadowGenerators.push(sg);
  68473. }
  68474. }
  68475. // Lights exclusions / inclusions
  68476. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68477. var light_2 = scene.lights[index];
  68478. // Excluded check
  68479. if (light_2._excludedMeshesIds.length > 0) {
  68480. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68481. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68482. if (excludedMesh) {
  68483. light_2.excludedMeshes.push(excludedMesh);
  68484. }
  68485. }
  68486. light_2._excludedMeshesIds = [];
  68487. }
  68488. // Included check
  68489. if (light_2._includedOnlyMeshesIds.length > 0) {
  68490. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68491. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68492. if (includedOnlyMesh) {
  68493. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68494. }
  68495. }
  68496. light_2._includedOnlyMeshesIds = [];
  68497. }
  68498. }
  68499. // Effect layers
  68500. if (parsedData.effectLayers) {
  68501. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68502. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68503. container.effectLayers.push(effectLayer);
  68504. }
  68505. }
  68506. // Actions (scene)
  68507. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68508. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68509. }
  68510. if (!addToScene) {
  68511. container.removeAllFromScene();
  68512. }
  68513. }
  68514. catch (err) {
  68515. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68516. if (onError) {
  68517. onError(msg, err);
  68518. }
  68519. else {
  68520. BABYLON.Tools.Log(msg);
  68521. throw err;
  68522. }
  68523. }
  68524. finally {
  68525. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68526. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68527. }
  68528. }
  68529. return container;
  68530. };
  68531. BABYLON.SceneLoader.RegisterPlugin({
  68532. name: "babylon.js",
  68533. extensions: ".babylon",
  68534. canDirectLoad: function (data) {
  68535. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68536. return true;
  68537. }
  68538. return false;
  68539. },
  68540. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68541. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68542. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68543. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68544. // and avoid problems with multiple concurrent .babylon loads.
  68545. var log = "importMesh has failed JSON parse";
  68546. try {
  68547. var parsedData = JSON.parse(data);
  68548. log = "";
  68549. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68550. if (!meshesNames) {
  68551. meshesNames = null;
  68552. }
  68553. else if (!Array.isArray(meshesNames)) {
  68554. meshesNames = [meshesNames];
  68555. }
  68556. var hierarchyIds = new Array();
  68557. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68558. var loadedSkeletonsIds = [];
  68559. var loadedMaterialsIds = [];
  68560. var index;
  68561. var cache;
  68562. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68563. var parsedMesh = parsedData.meshes[index];
  68564. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68565. if (meshesNames !== null) {
  68566. // Remove found mesh name from list.
  68567. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68568. }
  68569. //Geometry?
  68570. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68571. //does the file contain geometries?
  68572. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68573. //find the correct geometry and add it to the scene
  68574. var found = false;
  68575. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68576. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68577. return;
  68578. }
  68579. else {
  68580. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68581. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68582. switch (geometryType) {
  68583. case "boxes":
  68584. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68585. break;
  68586. case "spheres":
  68587. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68588. break;
  68589. case "cylinders":
  68590. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68591. break;
  68592. case "toruses":
  68593. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68594. break;
  68595. case "grounds":
  68596. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68597. break;
  68598. case "planes":
  68599. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68600. break;
  68601. case "torusKnots":
  68602. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68603. break;
  68604. case "vertexData":
  68605. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68606. break;
  68607. }
  68608. found = true;
  68609. }
  68610. });
  68611. }
  68612. });
  68613. if (found === false) {
  68614. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68615. }
  68616. }
  68617. }
  68618. // Material ?
  68619. if (parsedMesh.materialId) {
  68620. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68621. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68622. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68623. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68624. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68625. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68626. var subMatId = parsedMultiMaterial.materials[matIndex];
  68627. loadedMaterialsIds.push(subMatId);
  68628. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68629. if (mat) {
  68630. log += "\n\tMaterial " + mat.toString(fullDetails);
  68631. }
  68632. }
  68633. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68634. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68635. if (mmat) {
  68636. materialFound = true;
  68637. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68638. }
  68639. break;
  68640. }
  68641. }
  68642. }
  68643. if (materialFound === false) {
  68644. loadedMaterialsIds.push(parsedMesh.materialId);
  68645. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68646. if (!mat) {
  68647. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68648. }
  68649. else {
  68650. log += "\n\tMaterial " + mat.toString(fullDetails);
  68651. }
  68652. }
  68653. }
  68654. // Skeleton ?
  68655. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68656. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68657. if (skeletonAlreadyLoaded === false) {
  68658. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68659. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68660. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68661. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68662. skeletons.push(skeleton);
  68663. loadedSkeletonsIds.push(parsedSkeleton.id);
  68664. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68665. }
  68666. }
  68667. }
  68668. }
  68669. // Morph targets ?
  68670. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68671. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68672. var managerData = _a[_i];
  68673. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68674. }
  68675. }
  68676. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68677. meshes.push(mesh);
  68678. log += "\n\tMesh " + mesh.toString(fullDetails);
  68679. }
  68680. }
  68681. // Connecting parents
  68682. var currentMesh;
  68683. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68684. currentMesh = scene.meshes[index];
  68685. if (currentMesh._waitingParentId) {
  68686. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68687. currentMesh._waitingParentId = null;
  68688. }
  68689. }
  68690. // freeze and compute world matrix application
  68691. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68692. currentMesh = scene.meshes[index];
  68693. if (currentMesh._waitingFreezeWorldMatrix) {
  68694. currentMesh.freezeWorldMatrix();
  68695. currentMesh._waitingFreezeWorldMatrix = null;
  68696. }
  68697. else {
  68698. currentMesh.computeWorldMatrix(true);
  68699. }
  68700. }
  68701. }
  68702. // Particles
  68703. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68704. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68705. var parsedParticleSystem = parsedData.particleSystems[index];
  68706. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68707. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68708. }
  68709. }
  68710. }
  68711. return true;
  68712. }
  68713. catch (err) {
  68714. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68715. if (onError) {
  68716. onError(msg, err);
  68717. }
  68718. else {
  68719. BABYLON.Tools.Log(msg);
  68720. throw err;
  68721. }
  68722. }
  68723. finally {
  68724. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68725. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68726. }
  68727. }
  68728. return false;
  68729. },
  68730. load: function (scene, data, rootUrl, onError) {
  68731. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68732. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68733. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68734. // and avoid problems with multiple concurrent .babylon loads.
  68735. var log = "importScene has failed JSON parse";
  68736. try {
  68737. var parsedData = JSON.parse(data);
  68738. log = "";
  68739. // Scene
  68740. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68741. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68742. }
  68743. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68744. scene.autoClear = parsedData.autoClear;
  68745. }
  68746. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68747. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68748. }
  68749. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68750. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68751. }
  68752. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68753. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68754. }
  68755. // Fog
  68756. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68757. scene.fogMode = parsedData.fogMode;
  68758. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68759. scene.fogStart = parsedData.fogStart;
  68760. scene.fogEnd = parsedData.fogEnd;
  68761. scene.fogDensity = parsedData.fogDensity;
  68762. log += "\tFog mode for scene: ";
  68763. switch (scene.fogMode) {
  68764. // getters not compiling, so using hardcoded
  68765. case 1:
  68766. log += "exp\n";
  68767. break;
  68768. case 2:
  68769. log += "exp2\n";
  68770. break;
  68771. case 3:
  68772. log += "linear\n";
  68773. break;
  68774. }
  68775. }
  68776. //Physics
  68777. if (parsedData.physicsEnabled) {
  68778. var physicsPlugin;
  68779. if (parsedData.physicsEngine === "cannon") {
  68780. physicsPlugin = new BABYLON.CannonJSPlugin();
  68781. }
  68782. else if (parsedData.physicsEngine === "oimo") {
  68783. physicsPlugin = new BABYLON.OimoJSPlugin();
  68784. }
  68785. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68786. //else - default engine, which is currently oimo
  68787. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68788. scene.enablePhysics(physicsGravity, physicsPlugin);
  68789. }
  68790. // Metadata
  68791. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68792. scene.metadata = parsedData.metadata;
  68793. }
  68794. //collisions, if defined. otherwise, default is true
  68795. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68796. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68797. }
  68798. scene.workerCollisions = !!parsedData.workerCollisions;
  68799. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68800. if (!container) {
  68801. return false;
  68802. }
  68803. if (parsedData.autoAnimate) {
  68804. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68805. }
  68806. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68807. scene.setActiveCameraByID(parsedData.activeCameraID);
  68808. }
  68809. // Environment texture
  68810. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68811. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68812. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68813. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68814. if (parsedData.environmentTextureRotationY) {
  68815. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68816. }
  68817. scene.environmentTexture = hdrTexture;
  68818. }
  68819. else {
  68820. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68821. if (parsedData.environmentTextureRotationY) {
  68822. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68823. }
  68824. scene.environmentTexture = cubeTexture;
  68825. }
  68826. if (parsedData.createDefaultSkybox === true) {
  68827. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68828. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68829. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68830. }
  68831. }
  68832. // Finish
  68833. return true;
  68834. }
  68835. catch (err) {
  68836. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68837. if (onError) {
  68838. onError(msg, err);
  68839. }
  68840. else {
  68841. BABYLON.Tools.Log(msg);
  68842. throw err;
  68843. }
  68844. }
  68845. finally {
  68846. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68847. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68848. }
  68849. }
  68850. return false;
  68851. },
  68852. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68853. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68854. return container;
  68855. }
  68856. });
  68857. })(BABYLON || (BABYLON = {}));
  68858. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68859. var BABYLON;
  68860. (function (BABYLON) {
  68861. var FilesInput = /** @class */ (function () {
  68862. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68863. this.onProcessFileCallback = function () { return true; };
  68864. this._engine = engine;
  68865. this._currentScene = scene;
  68866. this._sceneLoadedCallback = sceneLoadedCallback;
  68867. this._progressCallback = progressCallback;
  68868. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68869. this._textureLoadingCallback = textureLoadingCallback;
  68870. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68871. this._onReloadCallback = onReloadCallback;
  68872. this._errorCallback = errorCallback;
  68873. }
  68874. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68875. var _this = this;
  68876. if (elementToMonitor) {
  68877. this._elementToMonitor = elementToMonitor;
  68878. this._dragEnterHandler = function (e) { _this.drag(e); };
  68879. this._dragOverHandler = function (e) { _this.drag(e); };
  68880. this._dropHandler = function (e) { _this.drop(e); };
  68881. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68882. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68883. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68884. }
  68885. };
  68886. FilesInput.prototype.dispose = function () {
  68887. if (!this._elementToMonitor) {
  68888. return;
  68889. }
  68890. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68891. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68892. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68893. };
  68894. FilesInput.prototype.renderFunction = function () {
  68895. if (this._additionalRenderLoopLogicCallback) {
  68896. this._additionalRenderLoopLogicCallback();
  68897. }
  68898. if (this._currentScene) {
  68899. if (this._textureLoadingCallback) {
  68900. var remaining = this._currentScene.getWaitingItemsCount();
  68901. if (remaining > 0) {
  68902. this._textureLoadingCallback(remaining);
  68903. }
  68904. }
  68905. this._currentScene.render();
  68906. }
  68907. };
  68908. FilesInput.prototype.drag = function (e) {
  68909. e.stopPropagation();
  68910. e.preventDefault();
  68911. };
  68912. FilesInput.prototype.drop = function (eventDrop) {
  68913. eventDrop.stopPropagation();
  68914. eventDrop.preventDefault();
  68915. this.loadFiles(eventDrop);
  68916. };
  68917. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68918. var _this = this;
  68919. var reader = folder.createReader();
  68920. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68921. reader.readEntries(function (entries) {
  68922. remaining.count += entries.length;
  68923. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68924. var entry = entries_1[_i];
  68925. if (entry.isFile) {
  68926. entry.file(function (file) {
  68927. file.correctName = relativePath + file.name;
  68928. files.push(file);
  68929. if (--remaining.count === 0) {
  68930. callback();
  68931. }
  68932. });
  68933. }
  68934. else if (entry.isDirectory) {
  68935. _this._traverseFolder(entry, files, remaining, callback);
  68936. }
  68937. }
  68938. if (--remaining.count) {
  68939. callback();
  68940. }
  68941. });
  68942. };
  68943. FilesInput.prototype._processFiles = function (files) {
  68944. for (var i = 0; i < files.length; i++) {
  68945. var name = files[i].correctName.toLowerCase();
  68946. var extension = name.split('.').pop();
  68947. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68948. continue;
  68949. }
  68950. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68951. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68952. this._sceneFileToLoad = files[i];
  68953. }
  68954. else {
  68955. FilesInput.FilesToLoad[name] = files[i];
  68956. }
  68957. }
  68958. };
  68959. FilesInput.prototype.loadFiles = function (event) {
  68960. var _this = this;
  68961. if (this._startingProcessingFilesCallback)
  68962. this._startingProcessingFilesCallback();
  68963. // Handling data transfer via drag'n'drop
  68964. if (event && event.dataTransfer && event.dataTransfer.files) {
  68965. this._filesToLoad = event.dataTransfer.files;
  68966. }
  68967. // Handling files from input files
  68968. if (event && event.target && event.target.files) {
  68969. this._filesToLoad = event.target.files;
  68970. }
  68971. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68972. var files_1 = new Array();
  68973. var folders = [];
  68974. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68975. for (var i = 0; i < this._filesToLoad.length; i++) {
  68976. var fileToLoad = this._filesToLoad[i];
  68977. var name_1 = fileToLoad.name.toLowerCase();
  68978. var entry = void 0;
  68979. fileToLoad.correctName = name_1;
  68980. if (items) {
  68981. var item = items[i];
  68982. if (item.getAsEntry) {
  68983. entry = item.getAsEntry();
  68984. }
  68985. else if (item.webkitGetAsEntry) {
  68986. entry = item.webkitGetAsEntry();
  68987. }
  68988. }
  68989. if (!entry) {
  68990. files_1.push(fileToLoad);
  68991. }
  68992. else {
  68993. if (entry.isDirectory) {
  68994. folders.push(entry);
  68995. }
  68996. else {
  68997. files_1.push(fileToLoad);
  68998. }
  68999. }
  69000. }
  69001. if (folders.length === 0) {
  69002. this._processFiles(files_1);
  69003. this._processReload();
  69004. }
  69005. else {
  69006. var remaining = { count: folders.length };
  69007. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  69008. var folder = folders_1[_i];
  69009. this._traverseFolder(folder, files_1, remaining, function () {
  69010. _this._processFiles(files_1);
  69011. if (remaining.count === 0) {
  69012. _this._processReload();
  69013. }
  69014. });
  69015. }
  69016. }
  69017. }
  69018. };
  69019. FilesInput.prototype._processReload = function () {
  69020. if (this._onReloadCallback) {
  69021. this._onReloadCallback(this._sceneFileToLoad);
  69022. }
  69023. else {
  69024. this.reload();
  69025. }
  69026. };
  69027. FilesInput.prototype.reload = function () {
  69028. var _this = this;
  69029. // If a scene file has been provided
  69030. if (this._sceneFileToLoad) {
  69031. if (this._currentScene) {
  69032. if (BABYLON.Tools.errorsCount > 0) {
  69033. BABYLON.Tools.ClearLogCache();
  69034. }
  69035. this._engine.stopRenderLoop();
  69036. }
  69037. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69038. if (_this._progressCallback) {
  69039. _this._progressCallback(progress);
  69040. }
  69041. }).then(function (scene) {
  69042. if (_this._currentScene) {
  69043. _this._currentScene.dispose();
  69044. }
  69045. _this._currentScene = scene;
  69046. if (_this._sceneLoadedCallback) {
  69047. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69048. }
  69049. // Wait for textures and shaders to be ready
  69050. _this._currentScene.executeWhenReady(function () {
  69051. _this._engine.runRenderLoop(function () {
  69052. _this.renderFunction();
  69053. });
  69054. });
  69055. }).catch(function (error) {
  69056. if (_this._errorCallback) {
  69057. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69058. }
  69059. });
  69060. }
  69061. else {
  69062. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69063. }
  69064. };
  69065. FilesInput.FilesToLoad = {};
  69066. return FilesInput;
  69067. }());
  69068. BABYLON.FilesInput = FilesInput;
  69069. })(BABYLON || (BABYLON = {}));
  69070. //# sourceMappingURL=babylon.filesInput.js.map
  69071. var BABYLON;
  69072. (function (BABYLON) {
  69073. /**
  69074. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69075. * The underlying implementation relies on an associative array to ensure the best performances.
  69076. * The value can be anything including 'null' but except 'undefined'
  69077. */
  69078. var StringDictionary = /** @class */ (function () {
  69079. function StringDictionary() {
  69080. this._count = 0;
  69081. this._data = {};
  69082. }
  69083. /**
  69084. * This will clear this dictionary and copy the content from the 'source' one.
  69085. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69086. * @param source the dictionary to take the content from and copy to this dictionary
  69087. */
  69088. StringDictionary.prototype.copyFrom = function (source) {
  69089. var _this = this;
  69090. this.clear();
  69091. source.forEach(function (t, v) { return _this.add(t, v); });
  69092. };
  69093. /**
  69094. * Get a value based from its key
  69095. * @param key the given key to get the matching value from
  69096. * @return the value if found, otherwise undefined is returned
  69097. */
  69098. StringDictionary.prototype.get = function (key) {
  69099. var val = this._data[key];
  69100. if (val !== undefined) {
  69101. return val;
  69102. }
  69103. return undefined;
  69104. };
  69105. /**
  69106. * Get a value from its key or add it if it doesn't exist.
  69107. * This method will ensure you that a given key/data will be present in the dictionary.
  69108. * @param key the given key to get the matching value from
  69109. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69110. * The factory will only be invoked if there's no data for the given key.
  69111. * @return the value corresponding to the key.
  69112. */
  69113. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69114. var val = this.get(key);
  69115. if (val !== undefined) {
  69116. return val;
  69117. }
  69118. val = factory(key);
  69119. if (val) {
  69120. this.add(key, val);
  69121. }
  69122. return val;
  69123. };
  69124. /**
  69125. * Get a value from its key if present in the dictionary otherwise add it
  69126. * @param key the key to get the value from
  69127. * @param val if there's no such key/value pair in the dictionary add it with this value
  69128. * @return the value corresponding to the key
  69129. */
  69130. StringDictionary.prototype.getOrAdd = function (key, val) {
  69131. var curVal = this.get(key);
  69132. if (curVal !== undefined) {
  69133. return curVal;
  69134. }
  69135. this.add(key, val);
  69136. return val;
  69137. };
  69138. /**
  69139. * Check if there's a given key in the dictionary
  69140. * @param key the key to check for
  69141. * @return true if the key is present, false otherwise
  69142. */
  69143. StringDictionary.prototype.contains = function (key) {
  69144. return this._data[key] !== undefined;
  69145. };
  69146. /**
  69147. * Add a new key and its corresponding value
  69148. * @param key the key to add
  69149. * @param value the value corresponding to the key
  69150. * @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
  69151. */
  69152. StringDictionary.prototype.add = function (key, value) {
  69153. if (this._data[key] !== undefined) {
  69154. return false;
  69155. }
  69156. this._data[key] = value;
  69157. ++this._count;
  69158. return true;
  69159. };
  69160. StringDictionary.prototype.set = function (key, value) {
  69161. if (this._data[key] === undefined) {
  69162. return false;
  69163. }
  69164. this._data[key] = value;
  69165. return true;
  69166. };
  69167. /**
  69168. * Get the element of the given key and remove it from the dictionary
  69169. * @param key
  69170. */
  69171. StringDictionary.prototype.getAndRemove = function (key) {
  69172. var val = this.get(key);
  69173. if (val !== undefined) {
  69174. delete this._data[key];
  69175. --this._count;
  69176. return val;
  69177. }
  69178. return null;
  69179. };
  69180. /**
  69181. * Remove a key/value from the dictionary.
  69182. * @param key the key to remove
  69183. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69184. */
  69185. StringDictionary.prototype.remove = function (key) {
  69186. if (this.contains(key)) {
  69187. delete this._data[key];
  69188. --this._count;
  69189. return true;
  69190. }
  69191. return false;
  69192. };
  69193. /**
  69194. * Clear the whole content of the dictionary
  69195. */
  69196. StringDictionary.prototype.clear = function () {
  69197. this._data = {};
  69198. this._count = 0;
  69199. };
  69200. Object.defineProperty(StringDictionary.prototype, "count", {
  69201. get: function () {
  69202. return this._count;
  69203. },
  69204. enumerable: true,
  69205. configurable: true
  69206. });
  69207. /**
  69208. * Execute a callback on each key/val of the dictionary.
  69209. * Note that you can remove any element in this dictionary in the callback implementation
  69210. * @param callback the callback to execute on a given key/value pair
  69211. */
  69212. StringDictionary.prototype.forEach = function (callback) {
  69213. for (var cur in this._data) {
  69214. var val = this._data[cur];
  69215. callback(cur, val);
  69216. }
  69217. };
  69218. /**
  69219. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69220. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69221. * Note that you can remove any element in this dictionary in the callback implementation
  69222. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69223. */
  69224. StringDictionary.prototype.first = function (callback) {
  69225. for (var cur in this._data) {
  69226. var val = this._data[cur];
  69227. var res = callback(cur, val);
  69228. if (res) {
  69229. return res;
  69230. }
  69231. }
  69232. return null;
  69233. };
  69234. return StringDictionary;
  69235. }());
  69236. BABYLON.StringDictionary = StringDictionary;
  69237. })(BABYLON || (BABYLON = {}));
  69238. //# sourceMappingURL=babylon.stringDictionary.js.map
  69239. var BABYLON;
  69240. (function (BABYLON) {
  69241. var Tags = /** @class */ (function () {
  69242. function Tags() {
  69243. }
  69244. Tags.EnableFor = function (obj) {
  69245. obj._tags = obj._tags || {};
  69246. obj.hasTags = function () {
  69247. return Tags.HasTags(obj);
  69248. };
  69249. obj.addTags = function (tagsString) {
  69250. return Tags.AddTagsTo(obj, tagsString);
  69251. };
  69252. obj.removeTags = function (tagsString) {
  69253. return Tags.RemoveTagsFrom(obj, tagsString);
  69254. };
  69255. obj.matchesTagsQuery = function (tagsQuery) {
  69256. return Tags.MatchesQuery(obj, tagsQuery);
  69257. };
  69258. };
  69259. Tags.DisableFor = function (obj) {
  69260. delete obj._tags;
  69261. delete obj.hasTags;
  69262. delete obj.addTags;
  69263. delete obj.removeTags;
  69264. delete obj.matchesTagsQuery;
  69265. };
  69266. Tags.HasTags = function (obj) {
  69267. if (!obj._tags) {
  69268. return false;
  69269. }
  69270. return !BABYLON.Tools.IsEmpty(obj._tags);
  69271. };
  69272. Tags.GetTags = function (obj, asString) {
  69273. if (asString === void 0) { asString = true; }
  69274. if (!obj._tags) {
  69275. return null;
  69276. }
  69277. if (asString) {
  69278. var tagsArray = [];
  69279. for (var tag in obj._tags) {
  69280. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69281. tagsArray.push(tag);
  69282. }
  69283. }
  69284. return tagsArray.join(" ");
  69285. }
  69286. else {
  69287. return obj._tags;
  69288. }
  69289. };
  69290. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69291. // a tag cannot start with '||', '&&', and '!'
  69292. // it cannot contain whitespaces
  69293. Tags.AddTagsTo = function (obj, tagsString) {
  69294. if (!tagsString) {
  69295. return;
  69296. }
  69297. if (typeof tagsString !== "string") {
  69298. return;
  69299. }
  69300. var tags = tagsString.split(" ");
  69301. tags.forEach(function (tag, index, array) {
  69302. Tags._AddTagTo(obj, tag);
  69303. });
  69304. };
  69305. Tags._AddTagTo = function (obj, tag) {
  69306. tag = tag.trim();
  69307. if (tag === "" || tag === "true" || tag === "false") {
  69308. return;
  69309. }
  69310. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69311. return;
  69312. }
  69313. Tags.EnableFor(obj);
  69314. obj._tags[tag] = true;
  69315. };
  69316. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69317. if (!Tags.HasTags(obj)) {
  69318. return;
  69319. }
  69320. var tags = tagsString.split(" ");
  69321. for (var t in tags) {
  69322. Tags._RemoveTagFrom(obj, tags[t]);
  69323. }
  69324. };
  69325. Tags._RemoveTagFrom = function (obj, tag) {
  69326. delete obj._tags[tag];
  69327. };
  69328. Tags.MatchesQuery = function (obj, tagsQuery) {
  69329. if (tagsQuery === undefined) {
  69330. return true;
  69331. }
  69332. if (tagsQuery === "") {
  69333. return Tags.HasTags(obj);
  69334. }
  69335. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69336. };
  69337. return Tags;
  69338. }());
  69339. BABYLON.Tags = Tags;
  69340. })(BABYLON || (BABYLON = {}));
  69341. //# sourceMappingURL=babylon.tags.js.map
  69342. var BABYLON;
  69343. (function (BABYLON) {
  69344. /**
  69345. * Class used to evalaute queries containing `and` and `or` operators
  69346. */
  69347. var AndOrNotEvaluator = /** @class */ (function () {
  69348. function AndOrNotEvaluator() {
  69349. }
  69350. /**
  69351. * Evaluate a query
  69352. * @param query defines the query to evaluate
  69353. * @param evaluateCallback defines the callback used to filter result
  69354. * @returns true if the query matches
  69355. */
  69356. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69357. if (!query.match(/\([^\(\)]*\)/g)) {
  69358. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69359. }
  69360. else {
  69361. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69362. // remove parenthesis
  69363. r = r.slice(1, r.length - 1);
  69364. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69365. });
  69366. }
  69367. if (query === "true") {
  69368. return true;
  69369. }
  69370. if (query === "false") {
  69371. return false;
  69372. }
  69373. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69374. };
  69375. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69376. evaluateCallback = evaluateCallback || (function (r) {
  69377. return r === "true" ? true : false;
  69378. });
  69379. var result;
  69380. var or = parenthesisContent.split("||");
  69381. for (var i in or) {
  69382. if (or.hasOwnProperty(i)) {
  69383. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69384. var and = ori.split("&&");
  69385. if (and.length > 1) {
  69386. for (var j = 0; j < and.length; ++j) {
  69387. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69388. if (andj !== "true" && andj !== "false") {
  69389. if (andj[0] === "!") {
  69390. result = !evaluateCallback(andj.substring(1));
  69391. }
  69392. else {
  69393. result = evaluateCallback(andj);
  69394. }
  69395. }
  69396. else {
  69397. result = andj === "true" ? true : false;
  69398. }
  69399. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69400. ori = "false";
  69401. break;
  69402. }
  69403. }
  69404. }
  69405. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69406. result = true;
  69407. break;
  69408. }
  69409. // result equals false (or undefined)
  69410. if (ori !== "true" && ori !== "false") {
  69411. if (ori[0] === "!") {
  69412. result = !evaluateCallback(ori.substring(1));
  69413. }
  69414. else {
  69415. result = evaluateCallback(ori);
  69416. }
  69417. }
  69418. else {
  69419. result = ori === "true" ? true : false;
  69420. }
  69421. }
  69422. }
  69423. // the whole parenthesis scope is replaced by 'true' or 'false'
  69424. return result ? "true" : "false";
  69425. };
  69426. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69427. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69428. // remove whitespaces
  69429. r = r.replace(/[\s]/g, function () { return ""; });
  69430. return r.length % 2 ? "!" : "";
  69431. });
  69432. booleanString = booleanString.trim();
  69433. if (booleanString === "!true") {
  69434. booleanString = "false";
  69435. }
  69436. else if (booleanString === "!false") {
  69437. booleanString = "true";
  69438. }
  69439. return booleanString;
  69440. };
  69441. return AndOrNotEvaluator;
  69442. }());
  69443. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69444. })(BABYLON || (BABYLON = {}));
  69445. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69446. var BABYLON;
  69447. (function (BABYLON) {
  69448. /**
  69449. * Class used to enable access to IndexedDB
  69450. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69451. */
  69452. var Database = /** @class */ (function () {
  69453. /**
  69454. * Creates a new Database
  69455. * @param urlToScene defines the url to load the scene
  69456. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69457. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69458. */
  69459. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69460. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69461. var _this = this;
  69462. // Handling various flavors of prefixed version of IndexedDB
  69463. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69464. this.callbackManifestChecked = callbackManifestChecked;
  69465. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69466. this.db = null;
  69467. this._enableSceneOffline = false;
  69468. this._enableTexturesOffline = false;
  69469. this.manifestVersionFound = 0;
  69470. this.mustUpdateRessources = false;
  69471. this.hasReachedQuota = false;
  69472. if (!Database.IDBStorageEnabled) {
  69473. this.callbackManifestChecked(true);
  69474. }
  69475. else {
  69476. if (disableManifestCheck) {
  69477. this._enableSceneOffline = true;
  69478. this._enableTexturesOffline = true;
  69479. this.manifestVersionFound = 1;
  69480. BABYLON.Tools.SetImmediate(function () {
  69481. _this.callbackManifestChecked(true);
  69482. });
  69483. }
  69484. else {
  69485. this._checkManifestFile();
  69486. }
  69487. }
  69488. }
  69489. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69490. /**
  69491. * Gets a boolean indicating if scene must be saved in the database
  69492. */
  69493. get: function () {
  69494. return this._enableSceneOffline;
  69495. },
  69496. enumerable: true,
  69497. configurable: true
  69498. });
  69499. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69500. /**
  69501. * Gets a boolean indicating if textures must be saved in the database
  69502. */
  69503. get: function () {
  69504. return this._enableTexturesOffline;
  69505. },
  69506. enumerable: true,
  69507. configurable: true
  69508. });
  69509. Database.prototype._checkManifestFile = function () {
  69510. var _this = this;
  69511. var noManifestFile = function () {
  69512. _this._enableSceneOffline = false;
  69513. _this._enableTexturesOffline = false;
  69514. _this.callbackManifestChecked(false);
  69515. };
  69516. var timeStampUsed = false;
  69517. var manifestURL = this.currentSceneUrl + ".manifest";
  69518. var xhr = new XMLHttpRequest();
  69519. if (navigator.onLine) {
  69520. // Adding a timestamp to by-pass browsers' cache
  69521. timeStampUsed = true;
  69522. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69523. }
  69524. xhr.open("GET", manifestURL, true);
  69525. xhr.addEventListener("load", function () {
  69526. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69527. try {
  69528. var manifestFile = JSON.parse(xhr.response);
  69529. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69530. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69531. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69532. _this.manifestVersionFound = manifestFile.version;
  69533. }
  69534. if (_this.callbackManifestChecked) {
  69535. _this.callbackManifestChecked(true);
  69536. }
  69537. }
  69538. catch (ex) {
  69539. noManifestFile();
  69540. }
  69541. }
  69542. else {
  69543. noManifestFile();
  69544. }
  69545. }, false);
  69546. xhr.addEventListener("error", function (event) {
  69547. if (timeStampUsed) {
  69548. timeStampUsed = false;
  69549. // Let's retry without the timeStamp
  69550. // It could fail when coupled with HTML5 Offline API
  69551. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69552. xhr.open("GET", retryManifestURL, true);
  69553. xhr.send();
  69554. }
  69555. else {
  69556. noManifestFile();
  69557. }
  69558. }, false);
  69559. try {
  69560. xhr.send();
  69561. }
  69562. catch (ex) {
  69563. BABYLON.Tools.Error("Error on XHR send request.");
  69564. this.callbackManifestChecked(false);
  69565. }
  69566. };
  69567. /**
  69568. * Open the database and make it available
  69569. * @param successCallback defines the callback to call on success
  69570. * @param errorCallback defines the callback to call on error
  69571. */
  69572. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69573. var _this = this;
  69574. var handleError = function () {
  69575. _this.isSupported = false;
  69576. if (errorCallback)
  69577. errorCallback();
  69578. };
  69579. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69580. // Your browser doesn't support IndexedDB
  69581. this.isSupported = false;
  69582. if (errorCallback)
  69583. errorCallback();
  69584. }
  69585. else {
  69586. // If the DB hasn't been opened or created yet
  69587. if (!this.db) {
  69588. this.hasReachedQuota = false;
  69589. this.isSupported = true;
  69590. var request = this.idbFactory.open("babylonjs", 1);
  69591. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69592. request.onerror = function (event) {
  69593. handleError();
  69594. };
  69595. // executes when a version change transaction cannot complete due to other active transactions
  69596. request.onblocked = function (event) {
  69597. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69598. handleError();
  69599. };
  69600. // DB has been opened successfully
  69601. request.onsuccess = function (event) {
  69602. _this.db = request.result;
  69603. successCallback();
  69604. };
  69605. // Initialization of the DB. Creating Scenes & Textures stores
  69606. request.onupgradeneeded = function (event) {
  69607. _this.db = (event.target).result;
  69608. if (_this.db) {
  69609. try {
  69610. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69611. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69612. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69613. }
  69614. catch (ex) {
  69615. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69616. handleError();
  69617. }
  69618. }
  69619. };
  69620. }
  69621. // DB has already been created and opened
  69622. else {
  69623. if (successCallback)
  69624. successCallback();
  69625. }
  69626. }
  69627. };
  69628. /**
  69629. * Loads an image from the database
  69630. * @param url defines the url to load from
  69631. * @param image defines the target DOM image
  69632. */
  69633. Database.prototype.loadImageFromDB = function (url, image) {
  69634. var _this = this;
  69635. var completeURL = Database._ReturnFullUrlLocation(url);
  69636. var saveAndLoadImage = function () {
  69637. if (!_this.hasReachedQuota && _this.db !== null) {
  69638. // the texture is not yet in the DB, let's try to save it
  69639. _this._saveImageIntoDBAsync(completeURL, image);
  69640. }
  69641. // If the texture is not in the DB and we've reached the DB quota limit
  69642. // let's load it directly from the web
  69643. else {
  69644. image.src = url;
  69645. }
  69646. };
  69647. if (!this.mustUpdateRessources) {
  69648. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69649. }
  69650. // First time we're download the images or update requested in the manifest file by a version change
  69651. else {
  69652. saveAndLoadImage();
  69653. }
  69654. };
  69655. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69656. if (this.isSupported && this.db !== null) {
  69657. var texture;
  69658. var transaction = this.db.transaction(["textures"]);
  69659. transaction.onabort = function (event) {
  69660. image.src = url;
  69661. };
  69662. transaction.oncomplete = function (event) {
  69663. var blobTextureURL;
  69664. if (texture) {
  69665. var URL = window.URL || window.webkitURL;
  69666. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69667. image.onerror = function () {
  69668. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69669. image.src = url;
  69670. };
  69671. image.src = blobTextureURL;
  69672. }
  69673. else {
  69674. notInDBCallback();
  69675. }
  69676. };
  69677. var getRequest = transaction.objectStore("textures").get(url);
  69678. getRequest.onsuccess = function (event) {
  69679. texture = (event.target).result;
  69680. };
  69681. getRequest.onerror = function (event) {
  69682. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69683. image.src = url;
  69684. };
  69685. }
  69686. else {
  69687. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69688. image.src = url;
  69689. }
  69690. };
  69691. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69692. var _this = this;
  69693. if (this.isSupported) {
  69694. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69695. var generateBlobUrl = function () {
  69696. var blobTextureURL;
  69697. if (blob) {
  69698. var URL = window.URL || window.webkitURL;
  69699. try {
  69700. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69701. }
  69702. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69703. catch (ex) {
  69704. blobTextureURL = URL.createObjectURL(blob);
  69705. }
  69706. }
  69707. if (blobTextureURL) {
  69708. image.src = blobTextureURL;
  69709. }
  69710. };
  69711. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69712. var xhr = new XMLHttpRequest(), blob;
  69713. xhr.open("GET", url, true);
  69714. xhr.responseType = "blob";
  69715. xhr.addEventListener("load", function () {
  69716. if (xhr.status === 200 && _this.db) {
  69717. // Blob as response (XHR2)
  69718. blob = xhr.response;
  69719. var transaction = _this.db.transaction(["textures"], "readwrite");
  69720. // the transaction could abort because of a QuotaExceededError error
  69721. transaction.onabort = function (event) {
  69722. try {
  69723. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69724. var srcElement = (event.srcElement || event.target);
  69725. var error = srcElement.error;
  69726. if (error && error.name === "QuotaExceededError") {
  69727. _this.hasReachedQuota = true;
  69728. }
  69729. }
  69730. catch (ex) { }
  69731. generateBlobUrl();
  69732. };
  69733. transaction.oncomplete = function (event) {
  69734. generateBlobUrl();
  69735. };
  69736. var newTexture = { textureUrl: url, data: blob };
  69737. try {
  69738. // Put the blob into the dabase
  69739. var addRequest = transaction.objectStore("textures").put(newTexture);
  69740. addRequest.onsuccess = function (event) {
  69741. };
  69742. addRequest.onerror = function (event) {
  69743. generateBlobUrl();
  69744. };
  69745. }
  69746. catch (ex) {
  69747. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69748. if (ex.code === 25) {
  69749. Database.IsUASupportingBlobStorage = false;
  69750. }
  69751. image.src = url;
  69752. }
  69753. }
  69754. else {
  69755. image.src = url;
  69756. }
  69757. }, false);
  69758. xhr.addEventListener("error", function (event) {
  69759. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69760. image.src = url;
  69761. }, false);
  69762. xhr.send();
  69763. }
  69764. else {
  69765. image.src = url;
  69766. }
  69767. }
  69768. else {
  69769. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69770. image.src = url;
  69771. }
  69772. };
  69773. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69774. var _this = this;
  69775. var updateVersion = function () {
  69776. // the version is not yet in the DB or we need to update it
  69777. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69778. };
  69779. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69780. };
  69781. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69782. var _this = this;
  69783. if (this.isSupported && this.db) {
  69784. var version;
  69785. try {
  69786. var transaction = this.db.transaction(["versions"]);
  69787. transaction.oncomplete = function (event) {
  69788. if (version) {
  69789. // If the version in the JSON file is different from the version in DB
  69790. if (_this.manifestVersionFound !== version.data) {
  69791. _this.mustUpdateRessources = true;
  69792. updateInDBCallback();
  69793. }
  69794. else {
  69795. callback(version.data);
  69796. }
  69797. }
  69798. // version was not found in DB
  69799. else {
  69800. _this.mustUpdateRessources = true;
  69801. updateInDBCallback();
  69802. }
  69803. };
  69804. transaction.onabort = function (event) {
  69805. callback(-1);
  69806. };
  69807. var getRequest = transaction.objectStore("versions").get(url);
  69808. getRequest.onsuccess = function (event) {
  69809. version = (event.target).result;
  69810. };
  69811. getRequest.onerror = function (event) {
  69812. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69813. callback(-1);
  69814. };
  69815. }
  69816. catch (ex) {
  69817. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69818. callback(-1);
  69819. }
  69820. }
  69821. else {
  69822. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69823. callback(-1);
  69824. }
  69825. };
  69826. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69827. var _this = this;
  69828. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69829. try {
  69830. // Open a transaction to the database
  69831. var transaction = this.db.transaction(["versions"], "readwrite");
  69832. // the transaction could abort because of a QuotaExceededError error
  69833. transaction.onabort = function (event) {
  69834. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69835. var error = event.srcElement['error'];
  69836. if (error && error.name === "QuotaExceededError") {
  69837. _this.hasReachedQuota = true;
  69838. }
  69839. }
  69840. catch (ex) { }
  69841. callback(-1);
  69842. };
  69843. transaction.oncomplete = function (event) {
  69844. callback(_this.manifestVersionFound);
  69845. };
  69846. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69847. // Put the scene into the database
  69848. var addRequest = transaction.objectStore("versions").put(newVersion);
  69849. addRequest.onsuccess = function (event) {
  69850. };
  69851. addRequest.onerror = function (event) {
  69852. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69853. };
  69854. }
  69855. catch (ex) {
  69856. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69857. callback(-1);
  69858. }
  69859. }
  69860. else {
  69861. callback(-1);
  69862. }
  69863. };
  69864. /**
  69865. * Loads a file from database
  69866. * @param url defines the URL to load from
  69867. * @param sceneLoaded defines a callback to call on success
  69868. * @param progressCallBack defines a callback to call when progress changed
  69869. * @param errorCallback defines a callback to call on error
  69870. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69871. */
  69872. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69873. var _this = this;
  69874. var completeUrl = Database._ReturnFullUrlLocation(url);
  69875. var saveAndLoadFile = function () {
  69876. // the scene is not yet in the DB, let's try to save it
  69877. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69878. };
  69879. this._checkVersionFromDB(completeUrl, function (version) {
  69880. if (version !== -1) {
  69881. if (!_this.mustUpdateRessources) {
  69882. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69883. }
  69884. else {
  69885. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69886. }
  69887. }
  69888. else {
  69889. if (errorCallback) {
  69890. errorCallback();
  69891. }
  69892. }
  69893. });
  69894. };
  69895. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69896. if (this.isSupported && this.db) {
  69897. var targetStore;
  69898. if (url.indexOf(".babylon") !== -1) {
  69899. targetStore = "scenes";
  69900. }
  69901. else {
  69902. targetStore = "textures";
  69903. }
  69904. var file;
  69905. var transaction = this.db.transaction([targetStore]);
  69906. transaction.oncomplete = function (event) {
  69907. if (file) {
  69908. callback(file.data);
  69909. }
  69910. // file was not found in DB
  69911. else {
  69912. notInDBCallback();
  69913. }
  69914. };
  69915. transaction.onabort = function (event) {
  69916. notInDBCallback();
  69917. };
  69918. var getRequest = transaction.objectStore(targetStore).get(url);
  69919. getRequest.onsuccess = function (event) {
  69920. file = (event.target).result;
  69921. };
  69922. getRequest.onerror = function (event) {
  69923. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69924. notInDBCallback();
  69925. };
  69926. }
  69927. else {
  69928. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69929. callback();
  69930. }
  69931. };
  69932. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69933. var _this = this;
  69934. if (this.isSupported) {
  69935. var targetStore;
  69936. if (url.indexOf(".babylon") !== -1) {
  69937. targetStore = "scenes";
  69938. }
  69939. else {
  69940. targetStore = "textures";
  69941. }
  69942. // Create XHR
  69943. var xhr = new XMLHttpRequest();
  69944. var fileData;
  69945. xhr.open("GET", url, true);
  69946. if (useArrayBuffer) {
  69947. xhr.responseType = "arraybuffer";
  69948. }
  69949. if (progressCallback) {
  69950. xhr.onprogress = progressCallback;
  69951. }
  69952. xhr.addEventListener("load", function () {
  69953. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69954. // Blob as response (XHR2)
  69955. //fileData = xhr.responseText;
  69956. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69957. if (!_this.hasReachedQuota && _this.db) {
  69958. // Open a transaction to the database
  69959. var transaction = _this.db.transaction([targetStore], "readwrite");
  69960. // the transaction could abort because of a QuotaExceededError error
  69961. transaction.onabort = function (event) {
  69962. try {
  69963. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69964. var error = event.srcElement['error'];
  69965. if (error && error.name === "QuotaExceededError") {
  69966. _this.hasReachedQuota = true;
  69967. }
  69968. }
  69969. catch (ex) { }
  69970. callback(fileData);
  69971. };
  69972. transaction.oncomplete = function (event) {
  69973. callback(fileData);
  69974. };
  69975. var newFile;
  69976. if (targetStore === "scenes") {
  69977. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69978. }
  69979. else {
  69980. newFile = { textureUrl: url, data: fileData };
  69981. }
  69982. try {
  69983. // Put the scene into the database
  69984. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69985. addRequest.onsuccess = function (event) {
  69986. };
  69987. addRequest.onerror = function (event) {
  69988. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69989. };
  69990. }
  69991. catch (ex) {
  69992. callback(fileData);
  69993. }
  69994. }
  69995. else {
  69996. callback(fileData);
  69997. }
  69998. }
  69999. else {
  70000. callback();
  70001. }
  70002. }, false);
  70003. xhr.addEventListener("error", function (event) {
  70004. BABYLON.Tools.Error("error on XHR request.");
  70005. callback();
  70006. }, false);
  70007. xhr.send();
  70008. }
  70009. else {
  70010. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70011. callback();
  70012. }
  70013. };
  70014. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  70015. Database.IsUASupportingBlobStorage = true;
  70016. /** Gets a boolean indicating if Database storate is enabled */
  70017. Database.IDBStorageEnabled = true;
  70018. Database._ParseURL = function (url) {
  70019. var a = document.createElement('a');
  70020. a.href = url;
  70021. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  70022. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  70023. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  70024. return absLocation;
  70025. };
  70026. Database._ReturnFullUrlLocation = function (url) {
  70027. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70028. return (Database._ParseURL(window.location.href) + url);
  70029. }
  70030. else {
  70031. return url;
  70032. }
  70033. };
  70034. return Database;
  70035. }());
  70036. BABYLON.Database = Database;
  70037. })(BABYLON || (BABYLON = {}));
  70038. //# sourceMappingURL=babylon.database.js.map
  70039. var BABYLON;
  70040. (function (BABYLON) {
  70041. var FresnelParameters = /** @class */ (function () {
  70042. function FresnelParameters() {
  70043. this._isEnabled = true;
  70044. this.leftColor = BABYLON.Color3.White();
  70045. this.rightColor = BABYLON.Color3.Black();
  70046. this.bias = 0;
  70047. this.power = 1;
  70048. }
  70049. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70050. get: function () {
  70051. return this._isEnabled;
  70052. },
  70053. set: function (value) {
  70054. if (this._isEnabled === value) {
  70055. return;
  70056. }
  70057. this._isEnabled = value;
  70058. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70059. },
  70060. enumerable: true,
  70061. configurable: true
  70062. });
  70063. FresnelParameters.prototype.clone = function () {
  70064. var newFresnelParameters = new FresnelParameters();
  70065. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70066. return newFresnelParameters;
  70067. };
  70068. FresnelParameters.prototype.serialize = function () {
  70069. var serializationObject = {};
  70070. serializationObject.isEnabled = this.isEnabled;
  70071. serializationObject.leftColor = this.leftColor.asArray();
  70072. serializationObject.rightColor = this.rightColor.asArray();
  70073. serializationObject.bias = this.bias;
  70074. serializationObject.power = this.power;
  70075. return serializationObject;
  70076. };
  70077. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70078. var fresnelParameters = new FresnelParameters();
  70079. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70080. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70081. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70082. fresnelParameters.bias = parsedFresnelParameters.bias;
  70083. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70084. return fresnelParameters;
  70085. };
  70086. return FresnelParameters;
  70087. }());
  70088. BABYLON.FresnelParameters = FresnelParameters;
  70089. })(BABYLON || (BABYLON = {}));
  70090. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70091. var BABYLON;
  70092. (function (BABYLON) {
  70093. var MultiMaterial = /** @class */ (function (_super) {
  70094. __extends(MultiMaterial, _super);
  70095. function MultiMaterial(name, scene) {
  70096. var _this = _super.call(this, name, scene, true) || this;
  70097. scene.multiMaterials.push(_this);
  70098. _this.subMaterials = new Array();
  70099. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70100. return _this;
  70101. }
  70102. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70103. get: function () {
  70104. return this._subMaterials;
  70105. },
  70106. set: function (value) {
  70107. this._subMaterials = value;
  70108. this._hookArray(value);
  70109. },
  70110. enumerable: true,
  70111. configurable: true
  70112. });
  70113. MultiMaterial.prototype._hookArray = function (array) {
  70114. var _this = this;
  70115. var oldPush = array.push;
  70116. array.push = function () {
  70117. var items = [];
  70118. for (var _i = 0; _i < arguments.length; _i++) {
  70119. items[_i] = arguments[_i];
  70120. }
  70121. var result = oldPush.apply(array, items);
  70122. _this._markAllSubMeshesAsTexturesDirty();
  70123. return result;
  70124. };
  70125. var oldSplice = array.splice;
  70126. array.splice = function (index, deleteCount) {
  70127. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70128. _this._markAllSubMeshesAsTexturesDirty();
  70129. return deleted;
  70130. };
  70131. };
  70132. // Properties
  70133. MultiMaterial.prototype.getSubMaterial = function (index) {
  70134. if (index < 0 || index >= this.subMaterials.length) {
  70135. return this.getScene().defaultMaterial;
  70136. }
  70137. return this.subMaterials[index];
  70138. };
  70139. MultiMaterial.prototype.getActiveTextures = function () {
  70140. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70141. if (subMaterial) {
  70142. return subMaterial.getActiveTextures();
  70143. }
  70144. else {
  70145. return [];
  70146. }
  70147. }));
  70148. var _a;
  70149. };
  70150. // Methods
  70151. MultiMaterial.prototype.getClassName = function () {
  70152. return "MultiMaterial";
  70153. };
  70154. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70155. for (var index = 0; index < this.subMaterials.length; index++) {
  70156. var subMaterial = this.subMaterials[index];
  70157. if (subMaterial) {
  70158. if (subMaterial.storeEffectOnSubMeshes) {
  70159. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70160. return false;
  70161. }
  70162. continue;
  70163. }
  70164. if (!subMaterial.isReady(mesh)) {
  70165. return false;
  70166. }
  70167. }
  70168. }
  70169. return true;
  70170. };
  70171. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70172. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70173. for (var index = 0; index < this.subMaterials.length; index++) {
  70174. var subMaterial = null;
  70175. var current = this.subMaterials[index];
  70176. if (cloneChildren && current) {
  70177. subMaterial = current.clone(name + "-" + current.name);
  70178. }
  70179. else {
  70180. subMaterial = this.subMaterials[index];
  70181. }
  70182. newMultiMaterial.subMaterials.push(subMaterial);
  70183. }
  70184. return newMultiMaterial;
  70185. };
  70186. MultiMaterial.prototype.serialize = function () {
  70187. var serializationObject = {};
  70188. serializationObject.name = this.name;
  70189. serializationObject.id = this.id;
  70190. if (BABYLON.Tags) {
  70191. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70192. }
  70193. serializationObject.materials = [];
  70194. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70195. var subMat = this.subMaterials[matIndex];
  70196. if (subMat) {
  70197. serializationObject.materials.push(subMat.id);
  70198. }
  70199. else {
  70200. serializationObject.materials.push(null);
  70201. }
  70202. }
  70203. return serializationObject;
  70204. };
  70205. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70206. var scene = this.getScene();
  70207. if (!scene) {
  70208. return;
  70209. }
  70210. var index = scene.multiMaterials.indexOf(this);
  70211. if (index >= 0) {
  70212. scene.multiMaterials.splice(index, 1);
  70213. }
  70214. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70215. };
  70216. return MultiMaterial;
  70217. }(BABYLON.Material));
  70218. BABYLON.MultiMaterial = MultiMaterial;
  70219. })(BABYLON || (BABYLON = {}));
  70220. //# sourceMappingURL=babylon.multiMaterial.js.map
  70221. var BABYLON;
  70222. (function (BABYLON) {
  70223. var FreeCameraTouchInput = /** @class */ (function () {
  70224. function FreeCameraTouchInput() {
  70225. this._offsetX = null;
  70226. this._offsetY = null;
  70227. this._pointerPressed = new Array();
  70228. this.touchAngularSensibility = 200000.0;
  70229. this.touchMoveSensibility = 250.0;
  70230. }
  70231. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70232. var _this = this;
  70233. var previousPosition = null;
  70234. if (this._pointerInput === undefined) {
  70235. this._onLostFocus = function (evt) {
  70236. _this._offsetX = null;
  70237. _this._offsetY = null;
  70238. };
  70239. this._pointerInput = function (p, s) {
  70240. var evt = p.event;
  70241. if (evt.pointerType === "mouse") {
  70242. return;
  70243. }
  70244. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70245. if (!noPreventDefault) {
  70246. evt.preventDefault();
  70247. }
  70248. _this._pointerPressed.push(evt.pointerId);
  70249. if (_this._pointerPressed.length !== 1) {
  70250. return;
  70251. }
  70252. previousPosition = {
  70253. x: evt.clientX,
  70254. y: evt.clientY
  70255. };
  70256. }
  70257. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70258. if (!noPreventDefault) {
  70259. evt.preventDefault();
  70260. }
  70261. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70262. if (index === -1) {
  70263. return;
  70264. }
  70265. _this._pointerPressed.splice(index, 1);
  70266. if (index != 0) {
  70267. return;
  70268. }
  70269. previousPosition = null;
  70270. _this._offsetX = null;
  70271. _this._offsetY = null;
  70272. }
  70273. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70274. if (!noPreventDefault) {
  70275. evt.preventDefault();
  70276. }
  70277. if (!previousPosition) {
  70278. return;
  70279. }
  70280. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70281. if (index != 0) {
  70282. return;
  70283. }
  70284. _this._offsetX = evt.clientX - previousPosition.x;
  70285. _this._offsetY = -(evt.clientY - previousPosition.y);
  70286. }
  70287. };
  70288. }
  70289. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70290. if (this._onLostFocus) {
  70291. element.addEventListener("blur", this._onLostFocus);
  70292. }
  70293. };
  70294. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70295. if (this._pointerInput && element) {
  70296. if (this._observer) {
  70297. this.camera.getScene().onPointerObservable.remove(this._observer);
  70298. this._observer = null;
  70299. }
  70300. if (this._onLostFocus) {
  70301. element.removeEventListener("blur", this._onLostFocus);
  70302. this._onLostFocus = null;
  70303. }
  70304. this._pointerPressed = [];
  70305. this._offsetX = null;
  70306. this._offsetY = null;
  70307. }
  70308. };
  70309. FreeCameraTouchInput.prototype.checkInputs = function () {
  70310. if (this._offsetX && this._offsetY) {
  70311. var camera = this.camera;
  70312. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70313. if (this._pointerPressed.length > 1) {
  70314. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70315. }
  70316. else {
  70317. var speed = camera._computeLocalCameraSpeed();
  70318. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70319. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70320. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70321. }
  70322. }
  70323. };
  70324. FreeCameraTouchInput.prototype.getClassName = function () {
  70325. return "FreeCameraTouchInput";
  70326. };
  70327. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70328. return "touch";
  70329. };
  70330. __decorate([
  70331. BABYLON.serialize()
  70332. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70333. __decorate([
  70334. BABYLON.serialize()
  70335. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70336. return FreeCameraTouchInput;
  70337. }());
  70338. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70339. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70340. })(BABYLON || (BABYLON = {}));
  70341. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70342. var BABYLON;
  70343. (function (BABYLON) {
  70344. // We're mainly based on the logic defined into the FreeCamera code
  70345. var TouchCamera = /** @class */ (function (_super) {
  70346. __extends(TouchCamera, _super);
  70347. //-- end properties for backward compatibility for inputs
  70348. function TouchCamera(name, position, scene) {
  70349. var _this = _super.call(this, name, position, scene) || this;
  70350. _this.inputs.addTouch();
  70351. _this._setupInputs();
  70352. return _this;
  70353. }
  70354. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70355. //-- Begin properties for backward compatibility for inputs
  70356. get: function () {
  70357. var touch = this.inputs.attached["touch"];
  70358. if (touch)
  70359. return touch.touchAngularSensibility;
  70360. return 0;
  70361. },
  70362. set: function (value) {
  70363. var touch = this.inputs.attached["touch"];
  70364. if (touch)
  70365. touch.touchAngularSensibility = value;
  70366. },
  70367. enumerable: true,
  70368. configurable: true
  70369. });
  70370. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70371. get: function () {
  70372. var touch = this.inputs.attached["touch"];
  70373. if (touch)
  70374. return touch.touchMoveSensibility;
  70375. return 0;
  70376. },
  70377. set: function (value) {
  70378. var touch = this.inputs.attached["touch"];
  70379. if (touch)
  70380. touch.touchMoveSensibility = value;
  70381. },
  70382. enumerable: true,
  70383. configurable: true
  70384. });
  70385. TouchCamera.prototype.getClassName = function () {
  70386. return "TouchCamera";
  70387. };
  70388. TouchCamera.prototype._setupInputs = function () {
  70389. var mouse = this.inputs.attached["mouse"];
  70390. if (mouse) {
  70391. mouse.touchEnabled = false;
  70392. }
  70393. };
  70394. return TouchCamera;
  70395. }(BABYLON.FreeCamera));
  70396. BABYLON.TouchCamera = TouchCamera;
  70397. })(BABYLON || (BABYLON = {}));
  70398. //# sourceMappingURL=babylon.touchCamera.js.map
  70399. var BABYLON;
  70400. (function (BABYLON) {
  70401. var ProceduralTexture = /** @class */ (function (_super) {
  70402. __extends(ProceduralTexture, _super);
  70403. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70404. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70405. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70406. if (isCube === void 0) { isCube = false; }
  70407. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70408. _this.isCube = isCube;
  70409. _this.isEnabled = true;
  70410. _this._currentRefreshId = -1;
  70411. _this._refreshRate = 1;
  70412. _this._vertexBuffers = {};
  70413. _this._uniforms = new Array();
  70414. _this._samplers = new Array();
  70415. _this._textures = {};
  70416. _this._floats = {};
  70417. _this._floatsArrays = {};
  70418. _this._colors3 = {};
  70419. _this._colors4 = {};
  70420. _this._vectors2 = {};
  70421. _this._vectors3 = {};
  70422. _this._matrices = {};
  70423. _this._fallbackTextureUsed = false;
  70424. scene.proceduralTextures.push(_this);
  70425. _this._engine = scene.getEngine();
  70426. _this.name = name;
  70427. _this.isRenderTarget = true;
  70428. _this._size = size;
  70429. _this._generateMipMaps = generateMipMaps;
  70430. _this.setFragment(fragment);
  70431. _this._fallbackTexture = fallbackTexture;
  70432. if (isCube) {
  70433. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70434. _this.setFloat("face", 0);
  70435. }
  70436. else {
  70437. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70438. }
  70439. // VBO
  70440. var vertices = [];
  70441. vertices.push(1, 1);
  70442. vertices.push(-1, 1);
  70443. vertices.push(-1, -1);
  70444. vertices.push(1, -1);
  70445. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70446. _this._createIndexBuffer();
  70447. return _this;
  70448. }
  70449. ProceduralTexture.prototype._createIndexBuffer = function () {
  70450. var engine = this._engine;
  70451. // Indices
  70452. var indices = [];
  70453. indices.push(0);
  70454. indices.push(1);
  70455. indices.push(2);
  70456. indices.push(0);
  70457. indices.push(2);
  70458. indices.push(3);
  70459. this._indexBuffer = engine.createIndexBuffer(indices);
  70460. };
  70461. ProceduralTexture.prototype._rebuild = function () {
  70462. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70463. if (vb) {
  70464. vb._rebuild();
  70465. }
  70466. this._createIndexBuffer();
  70467. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70468. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70469. }
  70470. };
  70471. ProceduralTexture.prototype.reset = function () {
  70472. if (this._effect === undefined) {
  70473. return;
  70474. }
  70475. var engine = this._engine;
  70476. engine._releaseEffect(this._effect);
  70477. };
  70478. ProceduralTexture.prototype.isReady = function () {
  70479. var _this = this;
  70480. var engine = this._engine;
  70481. var shaders;
  70482. if (!this._fragment) {
  70483. return false;
  70484. }
  70485. if (this._fallbackTextureUsed) {
  70486. return true;
  70487. }
  70488. if (this._fragment.fragmentElement !== undefined) {
  70489. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70490. }
  70491. else {
  70492. shaders = { vertex: "procedural", fragment: this._fragment };
  70493. }
  70494. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70495. _this.releaseInternalTexture();
  70496. if (_this._fallbackTexture) {
  70497. _this._texture = _this._fallbackTexture._texture;
  70498. if (_this._texture) {
  70499. _this._texture.incrementReferences();
  70500. }
  70501. }
  70502. _this._fallbackTextureUsed = true;
  70503. });
  70504. return this._effect.isReady();
  70505. };
  70506. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70507. this._currentRefreshId = -1;
  70508. };
  70509. ProceduralTexture.prototype.setFragment = function (fragment) {
  70510. this._fragment = fragment;
  70511. };
  70512. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70513. get: function () {
  70514. return this._refreshRate;
  70515. },
  70516. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70517. set: function (value) {
  70518. this._refreshRate = value;
  70519. this.resetRefreshCounter();
  70520. },
  70521. enumerable: true,
  70522. configurable: true
  70523. });
  70524. ProceduralTexture.prototype._shouldRender = function () {
  70525. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70526. return false;
  70527. }
  70528. if (this._fallbackTextureUsed) {
  70529. return false;
  70530. }
  70531. if (this._currentRefreshId === -1) { // At least render once
  70532. this._currentRefreshId = 1;
  70533. return true;
  70534. }
  70535. if (this.refreshRate === this._currentRefreshId) {
  70536. this._currentRefreshId = 1;
  70537. return true;
  70538. }
  70539. this._currentRefreshId++;
  70540. return false;
  70541. };
  70542. ProceduralTexture.prototype.getRenderSize = function () {
  70543. return this._size;
  70544. };
  70545. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70546. if (this._fallbackTextureUsed) {
  70547. return;
  70548. }
  70549. this.releaseInternalTexture();
  70550. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70551. };
  70552. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70553. if (this._uniforms.indexOf(uniformName) === -1) {
  70554. this._uniforms.push(uniformName);
  70555. }
  70556. };
  70557. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70558. if (this._samplers.indexOf(name) === -1) {
  70559. this._samplers.push(name);
  70560. }
  70561. this._textures[name] = texture;
  70562. return this;
  70563. };
  70564. ProceduralTexture.prototype.setFloat = function (name, value) {
  70565. this._checkUniform(name);
  70566. this._floats[name] = value;
  70567. return this;
  70568. };
  70569. ProceduralTexture.prototype.setFloats = function (name, value) {
  70570. this._checkUniform(name);
  70571. this._floatsArrays[name] = value;
  70572. return this;
  70573. };
  70574. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70575. this._checkUniform(name);
  70576. this._colors3[name] = value;
  70577. return this;
  70578. };
  70579. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70580. this._checkUniform(name);
  70581. this._colors4[name] = value;
  70582. return this;
  70583. };
  70584. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70585. this._checkUniform(name);
  70586. this._vectors2[name] = value;
  70587. return this;
  70588. };
  70589. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70590. this._checkUniform(name);
  70591. this._vectors3[name] = value;
  70592. return this;
  70593. };
  70594. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70595. this._checkUniform(name);
  70596. this._matrices[name] = value;
  70597. return this;
  70598. };
  70599. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70600. var scene = this.getScene();
  70601. if (!scene) {
  70602. return;
  70603. }
  70604. var engine = this._engine;
  70605. // Render
  70606. engine.enableEffect(this._effect);
  70607. engine.setState(false);
  70608. // Texture
  70609. for (var name in this._textures) {
  70610. this._effect.setTexture(name, this._textures[name]);
  70611. }
  70612. // Float
  70613. for (name in this._floats) {
  70614. this._effect.setFloat(name, this._floats[name]);
  70615. }
  70616. // Floats
  70617. for (name in this._floatsArrays) {
  70618. this._effect.setArray(name, this._floatsArrays[name]);
  70619. }
  70620. // Color3
  70621. for (name in this._colors3) {
  70622. this._effect.setColor3(name, this._colors3[name]);
  70623. }
  70624. // Color4
  70625. for (name in this._colors4) {
  70626. var color = this._colors4[name];
  70627. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70628. }
  70629. // Vector2
  70630. for (name in this._vectors2) {
  70631. this._effect.setVector2(name, this._vectors2[name]);
  70632. }
  70633. // Vector3
  70634. for (name in this._vectors3) {
  70635. this._effect.setVector3(name, this._vectors3[name]);
  70636. }
  70637. // Matrix
  70638. for (name in this._matrices) {
  70639. this._effect.setMatrix(name, this._matrices[name]);
  70640. }
  70641. if (!this._texture) {
  70642. return;
  70643. }
  70644. if (this.isCube) {
  70645. for (var face = 0; face < 6; face++) {
  70646. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70647. // VBOs
  70648. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70649. this._effect.setFloat("face", face);
  70650. // Clear
  70651. engine.clear(scene.clearColor, true, true, true);
  70652. // Draw order
  70653. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70654. // Mipmaps
  70655. if (face === 5) {
  70656. engine.generateMipMapsForCubemap(this._texture);
  70657. }
  70658. }
  70659. }
  70660. else {
  70661. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70662. // VBOs
  70663. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70664. // Clear
  70665. engine.clear(scene.clearColor, true, true, true);
  70666. // Draw order
  70667. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70668. }
  70669. // Unbind
  70670. engine.unBindFramebuffer(this._texture, this.isCube);
  70671. if (this.onGenerated) {
  70672. this.onGenerated();
  70673. }
  70674. };
  70675. ProceduralTexture.prototype.clone = function () {
  70676. var textureSize = this.getSize();
  70677. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70678. // Base texture
  70679. newTexture.hasAlpha = this.hasAlpha;
  70680. newTexture.level = this.level;
  70681. // RenderTarget Texture
  70682. newTexture.coordinatesMode = this.coordinatesMode;
  70683. return newTexture;
  70684. };
  70685. ProceduralTexture.prototype.dispose = function () {
  70686. var scene = this.getScene();
  70687. if (!scene) {
  70688. return;
  70689. }
  70690. var index = scene.proceduralTextures.indexOf(this);
  70691. if (index >= 0) {
  70692. scene.proceduralTextures.splice(index, 1);
  70693. }
  70694. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70695. if (vertexBuffer) {
  70696. vertexBuffer.dispose();
  70697. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70698. }
  70699. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70700. this._indexBuffer = null;
  70701. }
  70702. _super.prototype.dispose.call(this);
  70703. };
  70704. return ProceduralTexture;
  70705. }(BABYLON.Texture));
  70706. BABYLON.ProceduralTexture = ProceduralTexture;
  70707. })(BABYLON || (BABYLON = {}));
  70708. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70709. var BABYLON;
  70710. (function (BABYLON) {
  70711. var CustomProceduralTexture = /** @class */ (function (_super) {
  70712. __extends(CustomProceduralTexture, _super);
  70713. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70714. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70715. _this._animate = true;
  70716. _this._time = 0;
  70717. _this._texturePath = texturePath;
  70718. //Try to load json
  70719. _this.loadJson(texturePath);
  70720. _this.refreshRate = 1;
  70721. return _this;
  70722. }
  70723. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70724. var _this = this;
  70725. var noConfigFile = function () {
  70726. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70727. try {
  70728. _this.setFragment(_this._texturePath);
  70729. }
  70730. catch (ex) {
  70731. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70732. }
  70733. };
  70734. var configFileUrl = jsonUrl + "/config.json";
  70735. var xhr = new XMLHttpRequest();
  70736. xhr.open("GET", configFileUrl, true);
  70737. xhr.addEventListener("load", function () {
  70738. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70739. try {
  70740. _this._config = JSON.parse(xhr.response);
  70741. _this.updateShaderUniforms();
  70742. _this.updateTextures();
  70743. _this.setFragment(_this._texturePath + "/custom");
  70744. _this._animate = _this._config.animate;
  70745. _this.refreshRate = _this._config.refreshrate;
  70746. }
  70747. catch (ex) {
  70748. noConfigFile();
  70749. }
  70750. }
  70751. else {
  70752. noConfigFile();
  70753. }
  70754. }, false);
  70755. xhr.addEventListener("error", function () {
  70756. noConfigFile();
  70757. }, false);
  70758. try {
  70759. xhr.send();
  70760. }
  70761. catch (ex) {
  70762. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70763. }
  70764. };
  70765. CustomProceduralTexture.prototype.isReady = function () {
  70766. if (!_super.prototype.isReady.call(this)) {
  70767. return false;
  70768. }
  70769. for (var name in this._textures) {
  70770. var texture = this._textures[name];
  70771. if (!texture.isReady()) {
  70772. return false;
  70773. }
  70774. }
  70775. return true;
  70776. };
  70777. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70778. var scene = this.getScene();
  70779. if (this._animate && scene) {
  70780. this._time += scene.getAnimationRatio() * 0.03;
  70781. this.updateShaderUniforms();
  70782. }
  70783. _super.prototype.render.call(this, useCameraPostProcess);
  70784. };
  70785. CustomProceduralTexture.prototype.updateTextures = function () {
  70786. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70787. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70788. }
  70789. };
  70790. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70791. if (this._config) {
  70792. for (var j = 0; j < this._config.uniforms.length; j++) {
  70793. var uniform = this._config.uniforms[j];
  70794. switch (uniform.type) {
  70795. case "float":
  70796. this.setFloat(uniform.name, uniform.value);
  70797. break;
  70798. case "color3":
  70799. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70800. break;
  70801. case "color4":
  70802. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70803. break;
  70804. case "vector2":
  70805. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70806. break;
  70807. case "vector3":
  70808. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70809. break;
  70810. }
  70811. }
  70812. }
  70813. this.setFloat("time", this._time);
  70814. };
  70815. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70816. get: function () {
  70817. return this._animate;
  70818. },
  70819. set: function (value) {
  70820. this._animate = value;
  70821. },
  70822. enumerable: true,
  70823. configurable: true
  70824. });
  70825. return CustomProceduralTexture;
  70826. }(BABYLON.ProceduralTexture));
  70827. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70828. })(BABYLON || (BABYLON = {}));
  70829. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70830. var BABYLON;
  70831. (function (BABYLON) {
  70832. var FreeCameraGamepadInput = /** @class */ (function () {
  70833. function FreeCameraGamepadInput() {
  70834. this.gamepadAngularSensibility = 200;
  70835. this.gamepadMoveSensibility = 40;
  70836. // private members
  70837. this._cameraTransform = BABYLON.Matrix.Identity();
  70838. this._deltaTransform = BABYLON.Vector3.Zero();
  70839. this._vector3 = BABYLON.Vector3.Zero();
  70840. this._vector2 = BABYLON.Vector2.Zero();
  70841. }
  70842. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70843. var _this = this;
  70844. var manager = this.camera.getScene().gamepadManager;
  70845. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70846. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70847. // prioritize XBOX gamepads.
  70848. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70849. _this.gamepad = gamepad;
  70850. }
  70851. }
  70852. });
  70853. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70854. if (_this.gamepad === gamepad) {
  70855. _this.gamepad = null;
  70856. }
  70857. });
  70858. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70859. };
  70860. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70861. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70862. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70863. this.gamepad = null;
  70864. };
  70865. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70866. if (this.gamepad && this.gamepad.leftStick) {
  70867. var camera = this.camera;
  70868. var LSValues = this.gamepad.leftStick;
  70869. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70870. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70871. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70872. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70873. var RSValues = this.gamepad.rightStick;
  70874. if (RSValues) {
  70875. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70876. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70877. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70878. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70879. }
  70880. else {
  70881. RSValues = { x: 0, y: 0 };
  70882. }
  70883. if (!camera.rotationQuaternion) {
  70884. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70885. }
  70886. else {
  70887. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70888. }
  70889. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70890. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70891. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70892. camera.cameraDirection.addInPlace(this._deltaTransform);
  70893. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70894. camera.cameraRotation.addInPlace(this._vector2);
  70895. }
  70896. };
  70897. FreeCameraGamepadInput.prototype.getClassName = function () {
  70898. return "FreeCameraGamepadInput";
  70899. };
  70900. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70901. return "gamepad";
  70902. };
  70903. __decorate([
  70904. BABYLON.serialize()
  70905. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70906. __decorate([
  70907. BABYLON.serialize()
  70908. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70909. return FreeCameraGamepadInput;
  70910. }());
  70911. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70912. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70913. })(BABYLON || (BABYLON = {}));
  70914. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70915. var BABYLON;
  70916. (function (BABYLON) {
  70917. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70918. function ArcRotateCameraGamepadInput() {
  70919. this.gamepadRotationSensibility = 80;
  70920. this.gamepadMoveSensibility = 40;
  70921. }
  70922. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70923. var _this = this;
  70924. var manager = this.camera.getScene().gamepadManager;
  70925. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70926. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70927. // prioritize XBOX gamepads.
  70928. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70929. _this.gamepad = gamepad;
  70930. }
  70931. }
  70932. });
  70933. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70934. if (_this.gamepad === gamepad) {
  70935. _this.gamepad = null;
  70936. }
  70937. });
  70938. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70939. };
  70940. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70941. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70942. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70943. this.gamepad = null;
  70944. };
  70945. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70946. if (this.gamepad) {
  70947. var camera = this.camera;
  70948. var RSValues = this.gamepad.rightStick;
  70949. if (RSValues) {
  70950. if (RSValues.x != 0) {
  70951. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70952. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70953. camera.inertialAlphaOffset += normalizedRX;
  70954. }
  70955. }
  70956. if (RSValues.y != 0) {
  70957. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70958. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70959. camera.inertialBetaOffset += normalizedRY;
  70960. }
  70961. }
  70962. }
  70963. var LSValues = this.gamepad.leftStick;
  70964. if (LSValues && LSValues.y != 0) {
  70965. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70966. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70967. this.camera.inertialRadiusOffset -= normalizedLY;
  70968. }
  70969. }
  70970. }
  70971. };
  70972. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70973. return "ArcRotateCameraGamepadInput";
  70974. };
  70975. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70976. return "gamepad";
  70977. };
  70978. __decorate([
  70979. BABYLON.serialize()
  70980. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70981. __decorate([
  70982. BABYLON.serialize()
  70983. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70984. return ArcRotateCameraGamepadInput;
  70985. }());
  70986. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70987. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70988. })(BABYLON || (BABYLON = {}));
  70989. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70990. var BABYLON;
  70991. (function (BABYLON) {
  70992. var GamepadManager = /** @class */ (function () {
  70993. function GamepadManager(_scene) {
  70994. var _this = this;
  70995. this._scene = _scene;
  70996. this._babylonGamepads = [];
  70997. this._oneGamepadConnected = false;
  70998. this._isMonitoring = false;
  70999. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  71000. if (!BABYLON.Tools.IsWindowObjectExist()) {
  71001. this._gamepadEventSupported = false;
  71002. }
  71003. else {
  71004. this._gamepadEventSupported = 'GamepadEvent' in window;
  71005. this._gamepadSupport = (navigator.getGamepads ||
  71006. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  71007. }
  71008. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  71009. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  71010. for (var i in _this._babylonGamepads) {
  71011. var gamepad = _this._babylonGamepads[i];
  71012. if (gamepad && gamepad._isConnected) {
  71013. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  71014. }
  71015. }
  71016. });
  71017. this._onGamepadConnectedEvent = function (evt) {
  71018. var gamepad = evt.gamepad;
  71019. if (gamepad.index in _this._babylonGamepads) {
  71020. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71021. return;
  71022. }
  71023. }
  71024. var newGamepad;
  71025. if (_this._babylonGamepads[gamepad.index]) {
  71026. newGamepad = _this._babylonGamepads[gamepad.index];
  71027. newGamepad.browserGamepad = gamepad;
  71028. newGamepad._isConnected = true;
  71029. }
  71030. else {
  71031. newGamepad = _this._addNewGamepad(gamepad);
  71032. }
  71033. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71034. _this._startMonitoringGamepads();
  71035. };
  71036. this._onGamepadDisconnectedEvent = function (evt) {
  71037. var gamepad = evt.gamepad;
  71038. // Remove the gamepad from the list of gamepads to monitor.
  71039. for (var i in _this._babylonGamepads) {
  71040. if (_this._babylonGamepads[i].index === gamepad.index) {
  71041. var disconnectedGamepad = _this._babylonGamepads[i];
  71042. disconnectedGamepad._isConnected = false;
  71043. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71044. break;
  71045. }
  71046. }
  71047. };
  71048. if (this._gamepadSupport) {
  71049. //first add already-connected gamepads
  71050. this._updateGamepadObjects();
  71051. if (this._babylonGamepads.length) {
  71052. this._startMonitoringGamepads();
  71053. }
  71054. // Checking if the gamepad connected event is supported (like in Firefox)
  71055. if (this._gamepadEventSupported) {
  71056. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71057. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71058. }
  71059. else {
  71060. this._startMonitoringGamepads();
  71061. }
  71062. }
  71063. }
  71064. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71065. get: function () {
  71066. return this._babylonGamepads;
  71067. },
  71068. enumerable: true,
  71069. configurable: true
  71070. });
  71071. GamepadManager.prototype.getGamepadByType = function (type) {
  71072. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71073. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71074. var gamepad = _a[_i];
  71075. if (gamepad && gamepad.type === type) {
  71076. return gamepad;
  71077. }
  71078. }
  71079. return null;
  71080. };
  71081. GamepadManager.prototype.dispose = function () {
  71082. if (this._gamepadEventSupported) {
  71083. if (this._onGamepadConnectedEvent) {
  71084. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71085. }
  71086. if (this._onGamepadDisconnectedEvent) {
  71087. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71088. }
  71089. this._onGamepadConnectedEvent = null;
  71090. this._onGamepadDisconnectedEvent = null;
  71091. }
  71092. this._babylonGamepads.forEach(function (gamepad) {
  71093. gamepad.dispose();
  71094. });
  71095. this.onGamepadConnectedObservable.clear();
  71096. this.onGamepadDisconnectedObservable.clear();
  71097. this._oneGamepadConnected = false;
  71098. this._stopMonitoringGamepads();
  71099. this._babylonGamepads = [];
  71100. };
  71101. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71102. if (!this._oneGamepadConnected) {
  71103. this._oneGamepadConnected = true;
  71104. }
  71105. var newGamepad;
  71106. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71107. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71108. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71109. }
  71110. // if pose is supported, use the (WebVR) pose enabled controller
  71111. else if (gamepad.pose) {
  71112. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71113. }
  71114. else {
  71115. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71116. }
  71117. this._babylonGamepads[newGamepad.index] = newGamepad;
  71118. return newGamepad;
  71119. };
  71120. GamepadManager.prototype._startMonitoringGamepads = function () {
  71121. if (!this._isMonitoring) {
  71122. this._isMonitoring = true;
  71123. //back-comp
  71124. if (!this._scene) {
  71125. this._checkGamepadsStatus();
  71126. }
  71127. }
  71128. };
  71129. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71130. this._isMonitoring = false;
  71131. };
  71132. GamepadManager.prototype._checkGamepadsStatus = function () {
  71133. var _this = this;
  71134. // Hack to be compatible Chrome
  71135. this._updateGamepadObjects();
  71136. for (var i in this._babylonGamepads) {
  71137. var gamepad = this._babylonGamepads[i];
  71138. if (!gamepad || !gamepad.isConnected) {
  71139. continue;
  71140. }
  71141. gamepad.update();
  71142. }
  71143. if (this._isMonitoring && !this._scene) {
  71144. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71145. }
  71146. };
  71147. // This function is called only on Chrome, which does not properly support
  71148. // connection/disconnection events and forces you to recopy again the gamepad object
  71149. GamepadManager.prototype._updateGamepadObjects = function () {
  71150. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71151. for (var i = 0; i < gamepads.length; i++) {
  71152. var gamepad = gamepads[i];
  71153. if (gamepad) {
  71154. if (!this._babylonGamepads[gamepad.index]) {
  71155. var newGamepad = this._addNewGamepad(gamepad);
  71156. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71157. }
  71158. else {
  71159. // Forced to copy again this object for Chrome for unknown reason
  71160. this._babylonGamepads[i].browserGamepad = gamepad;
  71161. if (!this._babylonGamepads[i].isConnected) {
  71162. this._babylonGamepads[i]._isConnected = true;
  71163. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71164. }
  71165. }
  71166. }
  71167. }
  71168. };
  71169. return GamepadManager;
  71170. }());
  71171. BABYLON.GamepadManager = GamepadManager;
  71172. })(BABYLON || (BABYLON = {}));
  71173. //# sourceMappingURL=babylon.gamepadManager.js.map
  71174. var BABYLON;
  71175. (function (BABYLON) {
  71176. var StickValues = /** @class */ (function () {
  71177. function StickValues(x, y) {
  71178. this.x = x;
  71179. this.y = y;
  71180. }
  71181. return StickValues;
  71182. }());
  71183. BABYLON.StickValues = StickValues;
  71184. var Gamepad = /** @class */ (function () {
  71185. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71186. if (leftStickX === void 0) { leftStickX = 0; }
  71187. if (leftStickY === void 0) { leftStickY = 1; }
  71188. if (rightStickX === void 0) { rightStickX = 2; }
  71189. if (rightStickY === void 0) { rightStickY = 3; }
  71190. this.id = id;
  71191. this.index = index;
  71192. this.browserGamepad = browserGamepad;
  71193. this._isConnected = true;
  71194. this._invertLeftStickY = false;
  71195. this.type = Gamepad.GAMEPAD;
  71196. this._leftStickAxisX = leftStickX;
  71197. this._leftStickAxisY = leftStickY;
  71198. this._rightStickAxisX = rightStickX;
  71199. this._rightStickAxisY = rightStickY;
  71200. if (this.browserGamepad.axes.length >= 2) {
  71201. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71202. }
  71203. if (this.browserGamepad.axes.length >= 4) {
  71204. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71205. }
  71206. }
  71207. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71208. get: function () {
  71209. return this._isConnected;
  71210. },
  71211. enumerable: true,
  71212. configurable: true
  71213. });
  71214. Gamepad.prototype.onleftstickchanged = function (callback) {
  71215. this._onleftstickchanged = callback;
  71216. };
  71217. Gamepad.prototype.onrightstickchanged = function (callback) {
  71218. this._onrightstickchanged = callback;
  71219. };
  71220. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71221. get: function () {
  71222. return this._leftStick;
  71223. },
  71224. set: function (newValues) {
  71225. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71226. this._onleftstickchanged(newValues);
  71227. }
  71228. this._leftStick = newValues;
  71229. },
  71230. enumerable: true,
  71231. configurable: true
  71232. });
  71233. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71234. get: function () {
  71235. return this._rightStick;
  71236. },
  71237. set: function (newValues) {
  71238. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71239. this._onrightstickchanged(newValues);
  71240. }
  71241. this._rightStick = newValues;
  71242. },
  71243. enumerable: true,
  71244. configurable: true
  71245. });
  71246. Gamepad.prototype.update = function () {
  71247. if (this._leftStick) {
  71248. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71249. if (this._invertLeftStickY) {
  71250. this.leftStick.y *= -1;
  71251. }
  71252. }
  71253. if (this._rightStick) {
  71254. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71255. }
  71256. };
  71257. Gamepad.prototype.dispose = function () {
  71258. };
  71259. Gamepad.GAMEPAD = 0;
  71260. Gamepad.GENERIC = 1;
  71261. Gamepad.XBOX = 2;
  71262. Gamepad.POSE_ENABLED = 3;
  71263. return Gamepad;
  71264. }());
  71265. BABYLON.Gamepad = Gamepad;
  71266. var GenericPad = /** @class */ (function (_super) {
  71267. __extends(GenericPad, _super);
  71268. function GenericPad(id, index, browserGamepad) {
  71269. var _this = _super.call(this, id, index, browserGamepad) || this;
  71270. _this.onButtonDownObservable = new BABYLON.Observable();
  71271. _this.onButtonUpObservable = new BABYLON.Observable();
  71272. _this.type = Gamepad.GENERIC;
  71273. _this._buttons = new Array(browserGamepad.buttons.length);
  71274. return _this;
  71275. }
  71276. GenericPad.prototype.onbuttondown = function (callback) {
  71277. this._onbuttondown = callback;
  71278. };
  71279. GenericPad.prototype.onbuttonup = function (callback) {
  71280. this._onbuttonup = callback;
  71281. };
  71282. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71283. if (newValue !== currentValue) {
  71284. if (newValue === 1) {
  71285. if (this._onbuttondown) {
  71286. this._onbuttondown(buttonIndex);
  71287. }
  71288. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71289. }
  71290. if (newValue === 0) {
  71291. if (this._onbuttonup) {
  71292. this._onbuttonup(buttonIndex);
  71293. }
  71294. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71295. }
  71296. }
  71297. return newValue;
  71298. };
  71299. GenericPad.prototype.update = function () {
  71300. _super.prototype.update.call(this);
  71301. for (var index = 0; index < this._buttons.length; index++) {
  71302. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71303. }
  71304. };
  71305. GenericPad.prototype.dispose = function () {
  71306. _super.prototype.dispose.call(this);
  71307. this.onButtonDownObservable.clear();
  71308. this.onButtonUpObservable.clear();
  71309. };
  71310. return GenericPad;
  71311. }(Gamepad));
  71312. BABYLON.GenericPad = GenericPad;
  71313. })(BABYLON || (BABYLON = {}));
  71314. //# sourceMappingURL=babylon.gamepad.js.map
  71315. var BABYLON;
  71316. (function (BABYLON) {
  71317. /**
  71318. * Defines supported buttons for XBox360 compatible gamepads
  71319. */
  71320. var Xbox360Button;
  71321. (function (Xbox360Button) {
  71322. /** A */
  71323. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71324. /** B */
  71325. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71326. /** X */
  71327. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71328. /** Y */
  71329. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71330. /** Start */
  71331. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71332. /** Back */
  71333. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71334. /** Left button */
  71335. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71336. /** Right button */
  71337. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71338. /** Left stick */
  71339. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71340. /** Right stick */
  71341. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71342. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71343. /** Defines values for XBox360 DPad */
  71344. var Xbox360Dpad;
  71345. (function (Xbox360Dpad) {
  71346. /** Up */
  71347. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71348. /** Down */
  71349. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71350. /** Left */
  71351. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71352. /** Right */
  71353. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71354. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71355. /**
  71356. * Defines a XBox360 gamepad
  71357. */
  71358. var Xbox360Pad = /** @class */ (function (_super) {
  71359. __extends(Xbox360Pad, _super);
  71360. /**
  71361. * Creates a new XBox360 gamepad object
  71362. * @param id defines the id of this gamepad
  71363. * @param index defines its index
  71364. * @param gamepad defines the internal HTML gamepad object
  71365. * @param xboxOne defines if it is a XBox One gamepad
  71366. */
  71367. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71368. if (xboxOne === void 0) { xboxOne = false; }
  71369. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71370. _this._leftTrigger = 0;
  71371. _this._rightTrigger = 0;
  71372. /** Observable raised when a button is pressed */
  71373. _this.onButtonDownObservable = new BABYLON.Observable();
  71374. /** Observable raised when a button is released */
  71375. _this.onButtonUpObservable = new BABYLON.Observable();
  71376. /** Observable raised when a pad is pressed */
  71377. _this.onPadDownObservable = new BABYLON.Observable();
  71378. /** Observable raised when a pad is released */
  71379. _this.onPadUpObservable = new BABYLON.Observable();
  71380. _this._buttonA = 0;
  71381. _this._buttonB = 0;
  71382. _this._buttonX = 0;
  71383. _this._buttonY = 0;
  71384. _this._buttonBack = 0;
  71385. _this._buttonStart = 0;
  71386. _this._buttonLB = 0;
  71387. _this._buttonRB = 0;
  71388. _this._buttonLeftStick = 0;
  71389. _this._buttonRightStick = 0;
  71390. _this._dPadUp = 0;
  71391. _this._dPadDown = 0;
  71392. _this._dPadLeft = 0;
  71393. _this._dPadRight = 0;
  71394. _this._isXboxOnePad = false;
  71395. _this.type = BABYLON.Gamepad.XBOX;
  71396. _this._isXboxOnePad = xboxOne;
  71397. return _this;
  71398. }
  71399. /**
  71400. * Defines the callback to call when left trigger is pressed
  71401. * @param callback defines the callback to use
  71402. */
  71403. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71404. this._onlefttriggerchanged = callback;
  71405. };
  71406. /**
  71407. * Defines the callback to call when right trigger is pressed
  71408. * @param callback defines the callback to use
  71409. */
  71410. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71411. this._onrighttriggerchanged = callback;
  71412. };
  71413. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71414. /**
  71415. * Gets or sets left trigger value
  71416. */
  71417. get: function () {
  71418. return this._leftTrigger;
  71419. },
  71420. set: function (newValue) {
  71421. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71422. this._onlefttriggerchanged(newValue);
  71423. }
  71424. this._leftTrigger = newValue;
  71425. },
  71426. enumerable: true,
  71427. configurable: true
  71428. });
  71429. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71430. /**
  71431. * Gets or sets right trigger value
  71432. */
  71433. get: function () {
  71434. return this._rightTrigger;
  71435. },
  71436. set: function (newValue) {
  71437. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71438. this._onrighttriggerchanged(newValue);
  71439. }
  71440. this._rightTrigger = newValue;
  71441. },
  71442. enumerable: true,
  71443. configurable: true
  71444. });
  71445. /**
  71446. * Defines the callback to call when a button is pressed
  71447. * @param callback defines the callback to use
  71448. */
  71449. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71450. this._onbuttondown = callback;
  71451. };
  71452. /**
  71453. * Defines the callback to call when a button is released
  71454. * @param callback defines the callback to use
  71455. */
  71456. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71457. this._onbuttonup = callback;
  71458. };
  71459. /**
  71460. * Defines the callback to call when a pad is pressed
  71461. * @param callback defines the callback to use
  71462. */
  71463. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71464. this._ondpaddown = callback;
  71465. };
  71466. /**
  71467. * Defines the callback to call when a pad is released
  71468. * @param callback defines the callback to use
  71469. */
  71470. Xbox360Pad.prototype.ondpadup = function (callback) {
  71471. this._ondpadup = callback;
  71472. };
  71473. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71474. if (newValue !== currentValue) {
  71475. if (newValue === 1) {
  71476. if (this._onbuttondown) {
  71477. this._onbuttondown(buttonType);
  71478. }
  71479. this.onButtonDownObservable.notifyObservers(buttonType);
  71480. }
  71481. if (newValue === 0) {
  71482. if (this._onbuttonup) {
  71483. this._onbuttonup(buttonType);
  71484. }
  71485. this.onButtonUpObservable.notifyObservers(buttonType);
  71486. }
  71487. }
  71488. return newValue;
  71489. };
  71490. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71491. if (newValue !== currentValue) {
  71492. if (newValue === 1) {
  71493. if (this._ondpaddown) {
  71494. this._ondpaddown(buttonType);
  71495. }
  71496. this.onPadDownObservable.notifyObservers(buttonType);
  71497. }
  71498. if (newValue === 0) {
  71499. if (this._ondpadup) {
  71500. this._ondpadup(buttonType);
  71501. }
  71502. this.onPadUpObservable.notifyObservers(buttonType);
  71503. }
  71504. }
  71505. return newValue;
  71506. };
  71507. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71508. /** Gets or sets value of A button */
  71509. get: function () {
  71510. return this._buttonA;
  71511. },
  71512. set: function (value) {
  71513. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71514. },
  71515. enumerable: true,
  71516. configurable: true
  71517. });
  71518. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71519. /** Gets or sets value of B button */
  71520. get: function () {
  71521. return this._buttonB;
  71522. },
  71523. set: function (value) {
  71524. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71525. },
  71526. enumerable: true,
  71527. configurable: true
  71528. });
  71529. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71530. /** Gets or sets value of X button */
  71531. get: function () {
  71532. return this._buttonX;
  71533. },
  71534. set: function (value) {
  71535. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71536. },
  71537. enumerable: true,
  71538. configurable: true
  71539. });
  71540. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71541. /** Gets or sets value of Y button */
  71542. get: function () {
  71543. return this._buttonY;
  71544. },
  71545. set: function (value) {
  71546. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71547. },
  71548. enumerable: true,
  71549. configurable: true
  71550. });
  71551. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71552. /** Gets or sets value of Start button */
  71553. get: function () {
  71554. return this._buttonStart;
  71555. },
  71556. set: function (value) {
  71557. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71558. },
  71559. enumerable: true,
  71560. configurable: true
  71561. });
  71562. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71563. /** Gets or sets value of Back button */
  71564. get: function () {
  71565. return this._buttonBack;
  71566. },
  71567. set: function (value) {
  71568. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71569. },
  71570. enumerable: true,
  71571. configurable: true
  71572. });
  71573. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71574. /** Gets or sets value of Left button */
  71575. get: function () {
  71576. return this._buttonLB;
  71577. },
  71578. set: function (value) {
  71579. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71580. },
  71581. enumerable: true,
  71582. configurable: true
  71583. });
  71584. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71585. /** Gets or sets value of Right button */
  71586. get: function () {
  71587. return this._buttonRB;
  71588. },
  71589. set: function (value) {
  71590. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71591. },
  71592. enumerable: true,
  71593. configurable: true
  71594. });
  71595. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71596. /** Gets or sets value of left stick */
  71597. get: function () {
  71598. return this._buttonLeftStick;
  71599. },
  71600. set: function (value) {
  71601. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71602. },
  71603. enumerable: true,
  71604. configurable: true
  71605. });
  71606. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71607. /** Gets or sets value of right stick */
  71608. get: function () {
  71609. return this._buttonRightStick;
  71610. },
  71611. set: function (value) {
  71612. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71613. },
  71614. enumerable: true,
  71615. configurable: true
  71616. });
  71617. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71618. /** Gets or sets value of DPad up */
  71619. get: function () {
  71620. return this._dPadUp;
  71621. },
  71622. set: function (value) {
  71623. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71624. },
  71625. enumerable: true,
  71626. configurable: true
  71627. });
  71628. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71629. /** Gets or sets value of DPad down */
  71630. get: function () {
  71631. return this._dPadDown;
  71632. },
  71633. set: function (value) {
  71634. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71635. },
  71636. enumerable: true,
  71637. configurable: true
  71638. });
  71639. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71640. /** Gets or sets value of DPad left */
  71641. get: function () {
  71642. return this._dPadLeft;
  71643. },
  71644. set: function (value) {
  71645. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71646. },
  71647. enumerable: true,
  71648. configurable: true
  71649. });
  71650. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71651. /** Gets or sets value of DPad right */
  71652. get: function () {
  71653. return this._dPadRight;
  71654. },
  71655. set: function (value) {
  71656. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71657. },
  71658. enumerable: true,
  71659. configurable: true
  71660. });
  71661. /**
  71662. * Force the gamepad to synchronize with device values
  71663. */
  71664. Xbox360Pad.prototype.update = function () {
  71665. _super.prototype.update.call(this);
  71666. if (this._isXboxOnePad) {
  71667. this.buttonA = this.browserGamepad.buttons[0].value;
  71668. this.buttonB = this.browserGamepad.buttons[1].value;
  71669. this.buttonX = this.browserGamepad.buttons[2].value;
  71670. this.buttonY = this.browserGamepad.buttons[3].value;
  71671. this.buttonLB = this.browserGamepad.buttons[4].value;
  71672. this.buttonRB = this.browserGamepad.buttons[5].value;
  71673. this.leftTrigger = this.browserGamepad.axes[2];
  71674. this.rightTrigger = this.browserGamepad.axes[5];
  71675. this.buttonBack = this.browserGamepad.buttons[9].value;
  71676. this.buttonStart = this.browserGamepad.buttons[8].value;
  71677. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71678. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71679. this.dPadUp = this.browserGamepad.buttons[11].value;
  71680. this.dPadDown = this.browserGamepad.buttons[12].value;
  71681. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71682. this.dPadRight = this.browserGamepad.buttons[14].value;
  71683. }
  71684. else {
  71685. this.buttonA = this.browserGamepad.buttons[0].value;
  71686. this.buttonB = this.browserGamepad.buttons[1].value;
  71687. this.buttonX = this.browserGamepad.buttons[2].value;
  71688. this.buttonY = this.browserGamepad.buttons[3].value;
  71689. this.buttonLB = this.browserGamepad.buttons[4].value;
  71690. this.buttonRB = this.browserGamepad.buttons[5].value;
  71691. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71692. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71693. this.buttonBack = this.browserGamepad.buttons[8].value;
  71694. this.buttonStart = this.browserGamepad.buttons[9].value;
  71695. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71696. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71697. this.dPadUp = this.browserGamepad.buttons[12].value;
  71698. this.dPadDown = this.browserGamepad.buttons[13].value;
  71699. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71700. this.dPadRight = this.browserGamepad.buttons[15].value;
  71701. }
  71702. };
  71703. Xbox360Pad.prototype.dispose = function () {
  71704. _super.prototype.dispose.call(this);
  71705. this.onButtonDownObservable.clear();
  71706. this.onButtonUpObservable.clear();
  71707. this.onPadDownObservable.clear();
  71708. this.onPadUpObservable.clear();
  71709. };
  71710. return Xbox360Pad;
  71711. }(BABYLON.Gamepad));
  71712. BABYLON.Xbox360Pad = Xbox360Pad;
  71713. })(BABYLON || (BABYLON = {}));
  71714. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71715. var BABYLON;
  71716. (function (BABYLON) {
  71717. /**
  71718. * Defines the types of pose enabled controllers that are supported
  71719. */
  71720. var PoseEnabledControllerType;
  71721. (function (PoseEnabledControllerType) {
  71722. /**
  71723. * HTC Vive
  71724. */
  71725. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71726. /**
  71727. * Oculus Rift
  71728. */
  71729. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71730. /**
  71731. * Windows mixed reality
  71732. */
  71733. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71734. /**
  71735. * Samsung gear VR
  71736. */
  71737. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71738. /**
  71739. * Google Daydream
  71740. */
  71741. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71742. /**
  71743. * Generic
  71744. */
  71745. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71746. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71747. /**
  71748. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71749. */
  71750. var PoseEnabledControllerHelper = /** @class */ (function () {
  71751. function PoseEnabledControllerHelper() {
  71752. }
  71753. /**
  71754. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71755. * @param vrGamepad the gamepad to initialized
  71756. * @returns a vr controller of the type the gamepad identified as
  71757. */
  71758. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71759. // Oculus Touch
  71760. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71761. return new BABYLON.OculusTouchController(vrGamepad);
  71762. }
  71763. // Windows Mixed Reality controllers
  71764. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71765. return new BABYLON.WindowsMotionController(vrGamepad);
  71766. }
  71767. // HTC Vive
  71768. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71769. return new BABYLON.ViveController(vrGamepad);
  71770. }
  71771. // Samsung/Oculus Gear VR or Oculus Go
  71772. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71773. return new BABYLON.GearVRController(vrGamepad);
  71774. }
  71775. // Google Daydream
  71776. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71777. return new BABYLON.DaydreamController(vrGamepad);
  71778. }
  71779. // Generic
  71780. else {
  71781. return new BABYLON.GenericController(vrGamepad);
  71782. }
  71783. };
  71784. return PoseEnabledControllerHelper;
  71785. }());
  71786. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71787. /**
  71788. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71789. */
  71790. var PoseEnabledController = /** @class */ (function (_super) {
  71791. __extends(PoseEnabledController, _super);
  71792. /**
  71793. * Creates a new PoseEnabledController from a gamepad
  71794. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71795. */
  71796. function PoseEnabledController(browserGamepad) {
  71797. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71798. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71799. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71800. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71801. /**
  71802. * The device position in babylon space
  71803. */
  71804. _this.devicePosition = BABYLON.Vector3.Zero();
  71805. /**
  71806. * The device rotation in babylon space
  71807. */
  71808. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71809. /**
  71810. * The scale factor of the device in babylon space
  71811. */
  71812. _this.deviceScaleFactor = 1;
  71813. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71814. /**
  71815. * Internal, matrix used to convert room space to babylon space
  71816. */
  71817. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71818. /**
  71819. * Node to be used when casting a ray from the controller
  71820. */
  71821. _this._pointingPoseNode = null;
  71822. _this._workingMatrix = BABYLON.Matrix.Identity();
  71823. /**
  71824. * @hidden
  71825. */
  71826. _this._meshAttachedObservable = new BABYLON.Observable();
  71827. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71828. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71829. _this.position = BABYLON.Vector3.Zero();
  71830. _this.rotationQuaternion = new BABYLON.Quaternion();
  71831. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71832. _this._calculatedRotation = new BABYLON.Quaternion();
  71833. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71834. return _this;
  71835. }
  71836. /**
  71837. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71838. */
  71839. PoseEnabledController.prototype.update = function () {
  71840. _super.prototype.update.call(this);
  71841. var pose = this.browserGamepad.pose;
  71842. this.updateFromDevice(pose);
  71843. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71844. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71845. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71846. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71847. if (this._mesh) {
  71848. this._mesh.position.copyFrom(this.devicePosition);
  71849. if (this._mesh.rotationQuaternion) {
  71850. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71851. }
  71852. }
  71853. };
  71854. /**
  71855. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71856. * @param poseData raw pose fromthe device
  71857. */
  71858. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71859. if (poseData) {
  71860. this.rawPose = poseData;
  71861. if (poseData.position) {
  71862. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71863. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71864. this._deviceRoomPosition.z *= -1;
  71865. }
  71866. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71867. this._calculatedPosition.addInPlace(this.position);
  71868. }
  71869. var pose = this.rawPose;
  71870. if (poseData.orientation && pose.orientation) {
  71871. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71872. if (this._mesh) {
  71873. if (this._mesh.getScene().useRightHandedSystem) {
  71874. this._deviceRoomRotationQuaternion.z *= -1;
  71875. this._deviceRoomRotationQuaternion.w *= -1;
  71876. }
  71877. else {
  71878. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71879. }
  71880. }
  71881. // if the camera is set, rotate to the camera's rotation
  71882. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71883. }
  71884. }
  71885. };
  71886. /**
  71887. * Attaches a mesh to the controller
  71888. * @param mesh the mesh to be attached
  71889. */
  71890. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71891. if (this._mesh) {
  71892. this._mesh.parent = null;
  71893. }
  71894. this._mesh = mesh;
  71895. if (this._poseControlledCamera) {
  71896. this._mesh.parent = this._poseControlledCamera;
  71897. }
  71898. if (!this._mesh.rotationQuaternion) {
  71899. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71900. }
  71901. this._meshAttachedObservable.notifyObservers(mesh);
  71902. };
  71903. /**
  71904. * Attaches the controllers mesh to a camera
  71905. * @param camera the camera the mesh should be attached to
  71906. */
  71907. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71908. this._poseControlledCamera = camera;
  71909. if (this._mesh) {
  71910. this._mesh.parent = this._poseControlledCamera;
  71911. }
  71912. };
  71913. /**
  71914. * Disposes of the controller
  71915. */
  71916. PoseEnabledController.prototype.dispose = function () {
  71917. if (this._mesh) {
  71918. this._mesh.dispose();
  71919. }
  71920. this._mesh = null;
  71921. _super.prototype.dispose.call(this);
  71922. };
  71923. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71924. /**
  71925. * The mesh that is attached to the controller
  71926. */
  71927. get: function () {
  71928. return this._mesh;
  71929. },
  71930. enumerable: true,
  71931. configurable: true
  71932. });
  71933. /**
  71934. * Gets the ray of the controller in the direction the controller is pointing
  71935. * @param length the length the resulting ray should be
  71936. * @returns a ray in the direction the controller is pointing
  71937. */
  71938. PoseEnabledController.prototype.getForwardRay = function (length) {
  71939. if (length === void 0) { length = 100; }
  71940. if (!this.mesh) {
  71941. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71942. }
  71943. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71944. var origin = m.getTranslation();
  71945. var forward = new BABYLON.Vector3(0, 0, -1);
  71946. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71947. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71948. return new BABYLON.Ray(origin, direction, length);
  71949. };
  71950. /**
  71951. * Name of the child mesh that can be used to cast a ray from the controller
  71952. */
  71953. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71954. return PoseEnabledController;
  71955. }(BABYLON.Gamepad));
  71956. BABYLON.PoseEnabledController = PoseEnabledController;
  71957. })(BABYLON || (BABYLON = {}));
  71958. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71959. var BABYLON;
  71960. (function (BABYLON) {
  71961. /**
  71962. * Defines the WebVRController object that represents controllers tracked in 3D space
  71963. */
  71964. var WebVRController = /** @class */ (function (_super) {
  71965. __extends(WebVRController, _super);
  71966. /**
  71967. * Creates a new WebVRController from a gamepad
  71968. * @param vrGamepad the gamepad that the WebVRController should be created from
  71969. */
  71970. function WebVRController(vrGamepad) {
  71971. var _this = _super.call(this, vrGamepad) || this;
  71972. // Observables
  71973. /**
  71974. * Fired when the trigger state has changed
  71975. */
  71976. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71977. /**
  71978. * Fired when the main button state has changed
  71979. */
  71980. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71981. /**
  71982. * Fired when the secondary button state has changed
  71983. */
  71984. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71985. /**
  71986. * Fired when the pad state has changed
  71987. */
  71988. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71989. /**
  71990. * Fired when controllers stick values have changed
  71991. */
  71992. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71993. /**
  71994. * X and Y axis corrisponding to the controllers joystick
  71995. */
  71996. _this.pad = { x: 0, y: 0 };
  71997. // avoid GC, store state in a tmp object
  71998. _this._changes = {
  71999. pressChanged: false,
  72000. touchChanged: false,
  72001. valueChanged: false,
  72002. changed: false
  72003. };
  72004. _this._buttons = new Array(vrGamepad.buttons.length);
  72005. _this.hand = vrGamepad.hand;
  72006. return _this;
  72007. }
  72008. /**
  72009. * Fired when a controller button's state has changed
  72010. * @param callback the callback containing the button that was modified
  72011. */
  72012. WebVRController.prototype.onButtonStateChange = function (callback) {
  72013. this._onButtonStateChange = callback;
  72014. };
  72015. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72016. /**
  72017. * The default controller model for the controller
  72018. */
  72019. get: function () {
  72020. return this._defaultModel;
  72021. },
  72022. enumerable: true,
  72023. configurable: true
  72024. });
  72025. /**
  72026. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72027. */
  72028. WebVRController.prototype.update = function () {
  72029. _super.prototype.update.call(this);
  72030. for (var index = 0; index < this._buttons.length; index++) {
  72031. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72032. }
  72033. ;
  72034. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72035. this.pad.x = this.leftStick.x;
  72036. this.pad.y = this.leftStick.y;
  72037. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72038. }
  72039. };
  72040. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72041. if (!newState) {
  72042. newState = {
  72043. pressed: false,
  72044. touched: false,
  72045. value: 0
  72046. };
  72047. }
  72048. if (!currentState) {
  72049. this._buttons[buttonIndex] = {
  72050. pressed: newState.pressed,
  72051. touched: newState.touched,
  72052. value: newState.value
  72053. };
  72054. return;
  72055. }
  72056. this._checkChanges(newState, currentState);
  72057. if (this._changes.changed) {
  72058. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72059. this._handleButtonChange(buttonIndex, newState, this._changes);
  72060. }
  72061. this._buttons[buttonIndex].pressed = newState.pressed;
  72062. this._buttons[buttonIndex].touched = newState.touched;
  72063. // oculus triggers are never 0, thou not touched.
  72064. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72065. };
  72066. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72067. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72068. this._changes.touchChanged = newState.touched !== currentState.touched;
  72069. this._changes.valueChanged = newState.value !== currentState.value;
  72070. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72071. return this._changes;
  72072. };
  72073. /**
  72074. * Disposes of th webVRCOntroller
  72075. */
  72076. WebVRController.prototype.dispose = function () {
  72077. _super.prototype.dispose.call(this);
  72078. this.onTriggerStateChangedObservable.clear();
  72079. this.onMainButtonStateChangedObservable.clear();
  72080. this.onSecondaryButtonStateChangedObservable.clear();
  72081. this.onPadStateChangedObservable.clear();
  72082. this.onPadValuesChangedObservable.clear();
  72083. };
  72084. return WebVRController;
  72085. }(BABYLON.PoseEnabledController));
  72086. BABYLON.WebVRController = WebVRController;
  72087. })(BABYLON || (BABYLON = {}));
  72088. //# sourceMappingURL=babylon.webVRController.js.map
  72089. var BABYLON;
  72090. (function (BABYLON) {
  72091. /**
  72092. * Oculus Touch Controller
  72093. */
  72094. var OculusTouchController = /** @class */ (function (_super) {
  72095. __extends(OculusTouchController, _super);
  72096. /**
  72097. * Creates a new OculusTouchController from a gamepad
  72098. * @param vrGamepad the gamepad that the controller should be created from
  72099. */
  72100. function OculusTouchController(vrGamepad) {
  72101. var _this = _super.call(this, vrGamepad) || this;
  72102. /**
  72103. * Fired when the secondary trigger on this controller is modified
  72104. */
  72105. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72106. /**
  72107. * Fired when the thumb rest on this controller is modified
  72108. */
  72109. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72110. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72111. return _this;
  72112. }
  72113. /**
  72114. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72115. * @param scene scene in which to add meshes
  72116. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72117. */
  72118. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72119. var _this = this;
  72120. var meshName;
  72121. // Hand
  72122. if (this.hand === 'left') {
  72123. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72124. }
  72125. else { // Right is the default if no hand is specified
  72126. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72127. }
  72128. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72129. /*
  72130. Parent Mesh name: oculus_touch_left
  72131. - body
  72132. - trigger
  72133. - thumbstick
  72134. - grip
  72135. - button_y
  72136. - button_x
  72137. - button_enter
  72138. */
  72139. _this._defaultModel = newMeshes[1];
  72140. _this.attachToMesh(_this._defaultModel);
  72141. if (meshLoaded) {
  72142. meshLoaded(_this._defaultModel);
  72143. }
  72144. });
  72145. };
  72146. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72147. /**
  72148. * Fired when the A button on this controller is modified
  72149. */
  72150. get: function () {
  72151. if (this.hand === 'right') {
  72152. return this.onMainButtonStateChangedObservable;
  72153. }
  72154. else {
  72155. throw new Error('No A button on left hand');
  72156. }
  72157. },
  72158. enumerable: true,
  72159. configurable: true
  72160. });
  72161. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72162. /**
  72163. * Fired when the B button on this controller is modified
  72164. */
  72165. get: function () {
  72166. if (this.hand === 'right') {
  72167. return this.onSecondaryButtonStateChangedObservable;
  72168. }
  72169. else {
  72170. throw new Error('No B button on left hand');
  72171. }
  72172. },
  72173. enumerable: true,
  72174. configurable: true
  72175. });
  72176. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72177. /**
  72178. * Fired when the X button on this controller is modified
  72179. */
  72180. get: function () {
  72181. if (this.hand === 'left') {
  72182. return this.onMainButtonStateChangedObservable;
  72183. }
  72184. else {
  72185. throw new Error('No X button on right hand');
  72186. }
  72187. },
  72188. enumerable: true,
  72189. configurable: true
  72190. });
  72191. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72192. /**
  72193. * Fired when the Y button on this controller is modified
  72194. */
  72195. get: function () {
  72196. if (this.hand === 'left') {
  72197. return this.onSecondaryButtonStateChangedObservable;
  72198. }
  72199. else {
  72200. throw new Error('No Y button on right hand');
  72201. }
  72202. },
  72203. enumerable: true,
  72204. configurable: true
  72205. });
  72206. /**
  72207. * Called once for each button that changed state since the last frame
  72208. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72209. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72210. * 2) secondary trigger (same)
  72211. * 3) A (right) X (left), touch, pressed = value
  72212. * 4) B / Y
  72213. * 5) thumb rest
  72214. * @param buttonIdx Which button index changed
  72215. * @param state New state of the button
  72216. * @param changes Which properties on the state changed since last frame
  72217. */
  72218. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72219. var notifyObject = state; //{ state: state, changes: changes };
  72220. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72221. switch (buttonIdx) {
  72222. case 0:
  72223. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72224. return;
  72225. case 1: // index trigger
  72226. if (this._defaultModel) {
  72227. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72228. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72229. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72230. }
  72231. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72232. return;
  72233. case 2: // secondary trigger
  72234. if (this._defaultModel) {
  72235. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72236. }
  72237. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72238. return;
  72239. case 3:
  72240. if (this._defaultModel) {
  72241. if (notifyObject.pressed) {
  72242. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72243. }
  72244. else {
  72245. (this._defaultModel.getChildren()[1]).position.y = 0;
  72246. }
  72247. }
  72248. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72249. return;
  72250. case 4:
  72251. if (this._defaultModel) {
  72252. if (notifyObject.pressed) {
  72253. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72254. }
  72255. else {
  72256. (this._defaultModel.getChildren()[2]).position.y = 0;
  72257. }
  72258. }
  72259. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72260. return;
  72261. case 5:
  72262. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72263. return;
  72264. }
  72265. };
  72266. /**
  72267. * Base Url for the controller model.
  72268. */
  72269. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72270. /**
  72271. * File name for the left controller model.
  72272. */
  72273. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72274. /**
  72275. * File name for the right controller model.
  72276. */
  72277. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72278. return OculusTouchController;
  72279. }(BABYLON.WebVRController));
  72280. BABYLON.OculusTouchController = OculusTouchController;
  72281. })(BABYLON || (BABYLON = {}));
  72282. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72283. var BABYLON;
  72284. (function (BABYLON) {
  72285. /**
  72286. * Vive Controller
  72287. */
  72288. var ViveController = /** @class */ (function (_super) {
  72289. __extends(ViveController, _super);
  72290. /**
  72291. * Creates a new ViveController from a gamepad
  72292. * @param vrGamepad the gamepad that the controller should be created from
  72293. */
  72294. function ViveController(vrGamepad) {
  72295. var _this = _super.call(this, vrGamepad) || this;
  72296. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72297. _this._invertLeftStickY = true;
  72298. return _this;
  72299. }
  72300. /**
  72301. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72302. * @param scene scene in which to add meshes
  72303. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72304. */
  72305. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72306. var _this = this;
  72307. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72308. /*
  72309. Parent Mesh name: ViveWand
  72310. - body
  72311. - r_gripper
  72312. - l_gripper
  72313. - menu_button
  72314. - system_button
  72315. - trackpad
  72316. - trigger
  72317. - LED
  72318. */
  72319. _this._defaultModel = newMeshes[1];
  72320. _this.attachToMesh(_this._defaultModel);
  72321. if (meshLoaded) {
  72322. meshLoaded(_this._defaultModel);
  72323. }
  72324. });
  72325. };
  72326. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72327. /**
  72328. * Fired when the left button on this controller is modified
  72329. */
  72330. get: function () {
  72331. return this.onMainButtonStateChangedObservable;
  72332. },
  72333. enumerable: true,
  72334. configurable: true
  72335. });
  72336. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72337. /**
  72338. * Fired when the right button on this controller is modified
  72339. */
  72340. get: function () {
  72341. return this.onMainButtonStateChangedObservable;
  72342. },
  72343. enumerable: true,
  72344. configurable: true
  72345. });
  72346. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72347. /**
  72348. * Fired when the menu button on this controller is modified
  72349. */
  72350. get: function () {
  72351. return this.onSecondaryButtonStateChangedObservable;
  72352. },
  72353. enumerable: true,
  72354. configurable: true
  72355. });
  72356. /**
  72357. * Called once for each button that changed state since the last frame
  72358. * Vive mapping:
  72359. * 0: touchpad
  72360. * 1: trigger
  72361. * 2: left AND right buttons
  72362. * 3: menu button
  72363. * @param buttonIdx Which button index changed
  72364. * @param state New state of the button
  72365. * @param changes Which properties on the state changed since last frame
  72366. */
  72367. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72368. var notifyObject = state; //{ state: state, changes: changes };
  72369. switch (buttonIdx) {
  72370. case 0:
  72371. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72372. return;
  72373. case 1: // index trigger
  72374. if (this._defaultModel) {
  72375. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72376. }
  72377. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72378. return;
  72379. case 2: // left AND right button
  72380. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72381. return;
  72382. case 3:
  72383. if (this._defaultModel) {
  72384. if (notifyObject.pressed) {
  72385. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72386. }
  72387. else {
  72388. (this._defaultModel.getChildren()[2]).position.y = 0;
  72389. }
  72390. }
  72391. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72392. return;
  72393. }
  72394. };
  72395. /**
  72396. * Base Url for the controller model.
  72397. */
  72398. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72399. /**
  72400. * File name for the controller model.
  72401. */
  72402. ViveController.MODEL_FILENAME = 'wand.babylon';
  72403. return ViveController;
  72404. }(BABYLON.WebVRController));
  72405. BABYLON.ViveController = ViveController;
  72406. })(BABYLON || (BABYLON = {}));
  72407. //# sourceMappingURL=babylon.viveController.js.map
  72408. var BABYLON;
  72409. (function (BABYLON) {
  72410. /**
  72411. * Generic Controller
  72412. */
  72413. var GenericController = /** @class */ (function (_super) {
  72414. __extends(GenericController, _super);
  72415. /**
  72416. * Creates a new GenericController from a gamepad
  72417. * @param vrGamepad the gamepad that the controller should be created from
  72418. */
  72419. function GenericController(vrGamepad) {
  72420. return _super.call(this, vrGamepad) || this;
  72421. }
  72422. /**
  72423. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72424. * @param scene scene in which to add meshes
  72425. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72426. */
  72427. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72428. var _this = this;
  72429. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72430. _this._defaultModel = newMeshes[1];
  72431. _this.attachToMesh(_this._defaultModel);
  72432. if (meshLoaded) {
  72433. meshLoaded(_this._defaultModel);
  72434. }
  72435. });
  72436. };
  72437. /**
  72438. * Called once for each button that changed state since the last frame
  72439. * @param buttonIdx Which button index changed
  72440. * @param state New state of the button
  72441. * @param changes Which properties on the state changed since last frame
  72442. */
  72443. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72444. console.log("Button id: " + buttonIdx + "state: ");
  72445. console.dir(state);
  72446. };
  72447. /**
  72448. * Base Url for the controller model.
  72449. */
  72450. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72451. /**
  72452. * File name for the controller model.
  72453. */
  72454. GenericController.MODEL_FILENAME = 'generic.babylon';
  72455. return GenericController;
  72456. }(BABYLON.WebVRController));
  72457. BABYLON.GenericController = GenericController;
  72458. })(BABYLON || (BABYLON = {}));
  72459. //# sourceMappingURL=babylon.genericController.js.map
  72460. var BABYLON;
  72461. (function (BABYLON) {
  72462. /**
  72463. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72464. */
  72465. var LoadedMeshInfo = /** @class */ (function () {
  72466. function LoadedMeshInfo() {
  72467. /**
  72468. * Map of the button meshes contained in the controller
  72469. */
  72470. this.buttonMeshes = {};
  72471. /**
  72472. * Map of the axis meshes contained in the controller
  72473. */
  72474. this.axisMeshes = {};
  72475. }
  72476. return LoadedMeshInfo;
  72477. }());
  72478. /**
  72479. * Defines the WindowsMotionController object that the state of the windows motion controller
  72480. */
  72481. var WindowsMotionController = /** @class */ (function (_super) {
  72482. __extends(WindowsMotionController, _super);
  72483. /**
  72484. * Creates a new WindowsMotionController from a gamepad
  72485. * @param vrGamepad the gamepad that the controller should be created from
  72486. */
  72487. function WindowsMotionController(vrGamepad) {
  72488. var _this = _super.call(this, vrGamepad) || this;
  72489. _this._mapping = {
  72490. // Semantic button names
  72491. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72492. // A mapping of the button name to glTF model node name
  72493. // that should be transformed by button value.
  72494. buttonMeshNames: {
  72495. 'trigger': 'SELECT',
  72496. 'menu': 'MENU',
  72497. 'grip': 'GRASP',
  72498. 'thumbstick': 'THUMBSTICK_PRESS',
  72499. 'trackpad': 'TOUCHPAD_PRESS'
  72500. },
  72501. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72502. buttonObservableNames: {
  72503. 'trigger': 'onTriggerStateChangedObservable',
  72504. 'menu': 'onSecondaryButtonStateChangedObservable',
  72505. 'grip': 'onMainButtonStateChangedObservable',
  72506. 'thumbstick': 'onPadStateChangedObservable',
  72507. 'trackpad': 'onTrackpadChangedObservable'
  72508. },
  72509. // A mapping of the axis name to glTF model node name
  72510. // that should be transformed by axis value.
  72511. // This array mirrors the browserGamepad.axes array, such that
  72512. // the mesh corresponding to axis 0 is in this array index 0.
  72513. axisMeshNames: [
  72514. 'THUMBSTICK_X',
  72515. 'THUMBSTICK_Y',
  72516. 'TOUCHPAD_TOUCH_X',
  72517. 'TOUCHPAD_TOUCH_Y'
  72518. ],
  72519. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72520. };
  72521. /**
  72522. * Fired when the trackpad on this controller is clicked
  72523. */
  72524. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72525. /**
  72526. * Fired when the trackpad on this controller is modified
  72527. */
  72528. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72529. /**
  72530. * The current x and y values of this controller's trackpad
  72531. */
  72532. _this.trackpad = { x: 0, y: 0 };
  72533. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72534. _this._loadedMeshInfo = null;
  72535. return _this;
  72536. }
  72537. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72538. /**
  72539. * Fired when the trigger on this controller is modified
  72540. */
  72541. get: function () {
  72542. return this.onTriggerStateChangedObservable;
  72543. },
  72544. enumerable: true,
  72545. configurable: true
  72546. });
  72547. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72548. /**
  72549. * Fired when the menu button on this controller is modified
  72550. */
  72551. get: function () {
  72552. return this.onSecondaryButtonStateChangedObservable;
  72553. },
  72554. enumerable: true,
  72555. configurable: true
  72556. });
  72557. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72558. /**
  72559. * Fired when the grip button on this controller is modified
  72560. */
  72561. get: function () {
  72562. return this.onMainButtonStateChangedObservable;
  72563. },
  72564. enumerable: true,
  72565. configurable: true
  72566. });
  72567. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72568. /**
  72569. * Fired when the thumbstick button on this controller is modified
  72570. */
  72571. get: function () {
  72572. return this.onPadStateChangedObservable;
  72573. },
  72574. enumerable: true,
  72575. configurable: true
  72576. });
  72577. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72578. /**
  72579. * Fired when the touchpad button on this controller is modified
  72580. */
  72581. get: function () {
  72582. return this.onTrackpadChangedObservable;
  72583. },
  72584. enumerable: true,
  72585. configurable: true
  72586. });
  72587. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72588. /**
  72589. * Fired when the touchpad values on this controller are modified
  72590. */
  72591. get: function () {
  72592. return this.onTrackpadValuesChangedObservable;
  72593. },
  72594. enumerable: true,
  72595. configurable: true
  72596. });
  72597. WindowsMotionController.prototype._updateTrackpad = function () {
  72598. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72599. this.trackpad.x = this.browserGamepad["axes"][2];
  72600. this.trackpad.y = this.browserGamepad["axes"][3];
  72601. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72602. }
  72603. };
  72604. /**
  72605. * Called once per frame by the engine.
  72606. */
  72607. WindowsMotionController.prototype.update = function () {
  72608. _super.prototype.update.call(this);
  72609. if (this.browserGamepad.axes) {
  72610. this._updateTrackpad();
  72611. // Only need to animate axes if there is a loaded mesh
  72612. if (this._loadedMeshInfo) {
  72613. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72614. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72615. }
  72616. }
  72617. }
  72618. };
  72619. /**
  72620. * Called once for each button that changed state since the last frame
  72621. * @param buttonIdx Which button index changed
  72622. * @param state New state of the button
  72623. * @param changes Which properties on the state changed since last frame
  72624. */
  72625. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72626. var buttonName = this._mapping.buttons[buttonIdx];
  72627. if (!buttonName) {
  72628. return;
  72629. }
  72630. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72631. this._updateTrackpad();
  72632. // Only emit events for buttons that we know how to map from index to name
  72633. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72634. if (observable) {
  72635. observable.notifyObservers(state);
  72636. }
  72637. this._lerpButtonTransform(buttonName, state.value);
  72638. };
  72639. /**
  72640. * Moves the buttons on the controller mesh based on their current state
  72641. * @param buttonName the name of the button to move
  72642. * @param buttonValue the value of the button which determines the buttons new position
  72643. */
  72644. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72645. // If there is no loaded mesh, there is nothing to transform.
  72646. if (!this._loadedMeshInfo) {
  72647. return;
  72648. }
  72649. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72650. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72651. return;
  72652. }
  72653. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72654. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72655. };
  72656. /**
  72657. * Moves the axis on the controller mesh based on its current state
  72658. * @param axis the index of the axis
  72659. * @param axisValue the value of the axis which determines the meshes new position
  72660. * @hidden
  72661. */
  72662. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72663. if (!this._loadedMeshInfo) {
  72664. return;
  72665. }
  72666. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72667. if (!meshInfo) {
  72668. return;
  72669. }
  72670. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72671. return;
  72672. }
  72673. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72674. var lerpValue = axisValue * 0.5 + 0.5;
  72675. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72676. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72677. };
  72678. /**
  72679. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72680. * @param scene scene in which to add meshes
  72681. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72682. */
  72683. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72684. var _this = this;
  72685. if (forceDefault === void 0) { forceDefault = false; }
  72686. var path;
  72687. var filename;
  72688. // Checking if GLB loader is present
  72689. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72690. // Determine the device specific folder based on the ID suffix
  72691. var device = 'default';
  72692. if (this.id && !forceDefault) {
  72693. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72694. device = ((match && match[0]) || device);
  72695. }
  72696. // Hand
  72697. if (this.hand === 'left') {
  72698. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72699. }
  72700. else { // Right is the default if no hand is specified
  72701. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72702. }
  72703. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72704. }
  72705. else {
  72706. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72707. path = BABYLON.GenericController.MODEL_BASE_URL;
  72708. filename = BABYLON.GenericController.MODEL_FILENAME;
  72709. }
  72710. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72711. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72712. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72713. if (!_this._loadedMeshInfo) {
  72714. return;
  72715. }
  72716. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72717. _this.attachToMesh(_this._defaultModel);
  72718. if (meshLoaded) {
  72719. meshLoaded(_this._defaultModel);
  72720. }
  72721. }, null, function (scene, message) {
  72722. BABYLON.Tools.Log(message);
  72723. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72724. if (!forceDefault) {
  72725. _this.initControllerMesh(scene, meshLoaded, true);
  72726. }
  72727. });
  72728. };
  72729. /**
  72730. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72731. * can be transformed by button presses and axes values, based on this._mapping.
  72732. *
  72733. * @param scene scene in which the meshes exist
  72734. * @param meshes list of meshes that make up the controller model to process
  72735. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72736. */
  72737. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72738. var loadedMeshInfo = null;
  72739. // Create a new mesh to contain the glTF hierarchy
  72740. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72741. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72742. var childMesh = null;
  72743. for (var i = 0; i < meshes.length; i++) {
  72744. var mesh = meshes[i];
  72745. if (!mesh.parent) {
  72746. // Exclude controller meshes from picking results
  72747. mesh.isPickable = false;
  72748. // Handle root node, attach to the new parentMesh
  72749. childMesh = mesh;
  72750. break;
  72751. }
  72752. }
  72753. if (childMesh) {
  72754. childMesh.setParent(parentMesh);
  72755. // Create our mesh info. Note that this method will always return non-null.
  72756. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72757. }
  72758. else {
  72759. BABYLON.Tools.Warn('Could not find root node in model file.');
  72760. }
  72761. return loadedMeshInfo;
  72762. };
  72763. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72764. var loadedMeshInfo = new LoadedMeshInfo();
  72765. var i;
  72766. loadedMeshInfo.rootNode = rootNode;
  72767. // Reset the caches
  72768. loadedMeshInfo.buttonMeshes = {};
  72769. loadedMeshInfo.axisMeshes = {};
  72770. // Button Meshes
  72771. for (i = 0; i < this._mapping.buttons.length; i++) {
  72772. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72773. if (!buttonMeshName) {
  72774. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72775. continue;
  72776. }
  72777. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72778. if (!buttonMesh) {
  72779. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72780. continue;
  72781. }
  72782. var buttonMeshInfo = {
  72783. index: i,
  72784. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72785. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72786. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72787. };
  72788. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72789. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72790. }
  72791. else {
  72792. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72793. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72794. '(VALUE: ' + !!buttonMeshInfo.value +
  72795. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72796. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72797. ')');
  72798. }
  72799. }
  72800. // Axis Meshes
  72801. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72802. var axisMeshName = this._mapping.axisMeshNames[i];
  72803. if (!axisMeshName) {
  72804. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72805. continue;
  72806. }
  72807. var axisMesh = getChildByName(rootNode, axisMeshName);
  72808. if (!axisMesh) {
  72809. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72810. continue;
  72811. }
  72812. var axisMeshInfo = {
  72813. index: i,
  72814. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72815. min: getImmediateChildByName(axisMesh, 'MIN'),
  72816. max: getImmediateChildByName(axisMesh, 'MAX')
  72817. };
  72818. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72819. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72820. }
  72821. else {
  72822. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72823. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72824. '(VALUE: ' + !!axisMeshInfo.value +
  72825. ', MIN: ' + !!axisMeshInfo.min +
  72826. ', MAX:' + !!axisMeshInfo.max +
  72827. ')');
  72828. }
  72829. }
  72830. // Pointing Ray
  72831. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72832. if (!loadedMeshInfo.pointingPoseNode) {
  72833. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72834. }
  72835. return loadedMeshInfo;
  72836. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72837. function getChildByName(node, name) {
  72838. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72839. }
  72840. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72841. function getImmediateChildByName(node, name) {
  72842. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72843. }
  72844. };
  72845. /**
  72846. * Gets the ray of the controller in the direction the controller is pointing
  72847. * @param length the length the resulting ray should be
  72848. * @returns a ray in the direction the controller is pointing
  72849. */
  72850. WindowsMotionController.prototype.getForwardRay = function (length) {
  72851. if (length === void 0) { length = 100; }
  72852. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72853. return _super.prototype.getForwardRay.call(this, length);
  72854. }
  72855. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72856. var origin = m.getTranslation();
  72857. var forward = new BABYLON.Vector3(0, 0, -1);
  72858. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72859. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72860. return new BABYLON.Ray(origin, direction, length);
  72861. };
  72862. /**
  72863. * Disposes of the controller
  72864. */
  72865. WindowsMotionController.prototype.dispose = function () {
  72866. _super.prototype.dispose.call(this);
  72867. this.onTrackpadChangedObservable.clear();
  72868. };
  72869. /**
  72870. * The base url used to load the left and right controller models
  72871. */
  72872. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72873. /**
  72874. * The name of the left controller model file
  72875. */
  72876. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72877. /**
  72878. * The name of the right controller model file
  72879. */
  72880. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72881. /**
  72882. * The controller name prefix for this controller type
  72883. */
  72884. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72885. /**
  72886. * The controller id pattern for this controller type
  72887. */
  72888. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72889. return WindowsMotionController;
  72890. }(BABYLON.WebVRController));
  72891. BABYLON.WindowsMotionController = WindowsMotionController;
  72892. })(BABYLON || (BABYLON = {}));
  72893. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72894. var BABYLON;
  72895. (function (BABYLON) {
  72896. /**
  72897. * Gear VR Controller
  72898. */
  72899. var GearVRController = /** @class */ (function (_super) {
  72900. __extends(GearVRController, _super);
  72901. /**
  72902. * Creates a new GearVRController from a gamepad
  72903. * @param vrGamepad the gamepad that the controller should be created from
  72904. */
  72905. function GearVRController(vrGamepad) {
  72906. var _this = _super.call(this, vrGamepad) || this;
  72907. _this._buttonIndexToObservableNameMap = [
  72908. 'onTrackpadChangedObservable',
  72909. 'onTriggerStateChangedObservable' // Trigger
  72910. ];
  72911. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72912. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72913. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72914. return _this;
  72915. }
  72916. /**
  72917. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72918. * @param scene scene in which to add meshes
  72919. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72920. */
  72921. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72922. var _this = this;
  72923. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72924. _this._defaultModel = newMeshes[1];
  72925. _this.attachToMesh(_this._defaultModel);
  72926. if (meshLoaded) {
  72927. meshLoaded(_this._defaultModel);
  72928. }
  72929. });
  72930. };
  72931. /**
  72932. * Called once for each button that changed state since the last frame
  72933. * @param buttonIdx Which button index changed
  72934. * @param state New state of the button
  72935. * @param changes Which properties on the state changed since last frame
  72936. */
  72937. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72938. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72939. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72940. // Only emit events for buttons that we know how to map from index to observable
  72941. var observable = this[observableName];
  72942. if (observable) {
  72943. observable.notifyObservers(state);
  72944. }
  72945. }
  72946. };
  72947. /**
  72948. * Base Url for the controller model.
  72949. */
  72950. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72951. /**
  72952. * File name for the controller model.
  72953. */
  72954. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72955. /**
  72956. * Gamepad Id prefix used to identify this controller.
  72957. */
  72958. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72959. return GearVRController;
  72960. }(BABYLON.WebVRController));
  72961. BABYLON.GearVRController = GearVRController;
  72962. })(BABYLON || (BABYLON = {}));
  72963. //# sourceMappingURL=babylon.gearVRController.js.map
  72964. var BABYLON;
  72965. (function (BABYLON) {
  72966. /**
  72967. * Google Daydream controller
  72968. */
  72969. var DaydreamController = /** @class */ (function (_super) {
  72970. __extends(DaydreamController, _super);
  72971. /**
  72972. * Creates a new DaydreamController from a gamepad
  72973. * @param vrGamepad the gamepad that the controller should be created from
  72974. */
  72975. function DaydreamController(vrGamepad) {
  72976. var _this = _super.call(this, vrGamepad) || this;
  72977. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72978. return _this;
  72979. }
  72980. /**
  72981. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72982. * @param scene scene in which to add meshes
  72983. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72984. */
  72985. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72986. var _this = this;
  72987. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72988. _this._defaultModel = newMeshes[1];
  72989. _this.attachToMesh(_this._defaultModel);
  72990. if (meshLoaded) {
  72991. meshLoaded(_this._defaultModel);
  72992. }
  72993. });
  72994. };
  72995. /**
  72996. * Called once for each button that changed state since the last frame
  72997. * @param buttonIdx Which button index changed
  72998. * @param state New state of the button
  72999. * @param changes Which properties on the state changed since last frame
  73000. */
  73001. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73002. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73003. if (buttonIdx === 0) {
  73004. var observable = this.onTriggerStateChangedObservable;
  73005. if (observable) {
  73006. observable.notifyObservers(state);
  73007. }
  73008. }
  73009. else {
  73010. // If the app or home buttons are ever made available
  73011. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73012. }
  73013. };
  73014. /**
  73015. * Base Url for the controller model.
  73016. */
  73017. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73018. /**
  73019. * File name for the controller model.
  73020. */
  73021. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73022. /**
  73023. * Gamepad Id prefix used to identify Daydream Controller.
  73024. */
  73025. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73026. return DaydreamController;
  73027. }(BABYLON.WebVRController));
  73028. BABYLON.DaydreamController = DaydreamController;
  73029. })(BABYLON || (BABYLON = {}));
  73030. //# sourceMappingURL=babylon.daydreamController.js.map
  73031. var BABYLON;
  73032. (function (BABYLON) {
  73033. var FollowCamera = /** @class */ (function (_super) {
  73034. __extends(FollowCamera, _super);
  73035. function FollowCamera(name, position, scene, lockedTarget) {
  73036. if (lockedTarget === void 0) { lockedTarget = null; }
  73037. var _this = _super.call(this, name, position, scene) || this;
  73038. _this.radius = 12;
  73039. _this.rotationOffset = 0;
  73040. _this.heightOffset = 4;
  73041. _this.cameraAcceleration = 0.05;
  73042. _this.maxCameraSpeed = 20;
  73043. _this.lockedTarget = lockedTarget;
  73044. return _this;
  73045. }
  73046. FollowCamera.prototype.getRadians = function (degrees) {
  73047. return degrees * Math.PI / 180;
  73048. };
  73049. FollowCamera.prototype.follow = function (cameraTarget) {
  73050. if (!cameraTarget)
  73051. return;
  73052. var yRotation;
  73053. if (cameraTarget.rotationQuaternion) {
  73054. var rotMatrix = new BABYLON.Matrix();
  73055. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73056. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73057. }
  73058. else {
  73059. yRotation = cameraTarget.rotation.y;
  73060. }
  73061. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73062. var targetPosition = cameraTarget.getAbsolutePosition();
  73063. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73064. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73065. var dx = targetX - this.position.x;
  73066. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73067. var dz = (targetZ) - this.position.z;
  73068. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73069. var vy = dy * this.cameraAcceleration;
  73070. var vz = dz * this.cameraAcceleration * 2;
  73071. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73072. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73073. }
  73074. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73075. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73076. }
  73077. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73078. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73079. }
  73080. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73081. this.setTarget(targetPosition);
  73082. };
  73083. FollowCamera.prototype._checkInputs = function () {
  73084. _super.prototype._checkInputs.call(this);
  73085. if (this.lockedTarget) {
  73086. this.follow(this.lockedTarget);
  73087. }
  73088. };
  73089. FollowCamera.prototype.getClassName = function () {
  73090. return "FollowCamera";
  73091. };
  73092. __decorate([
  73093. BABYLON.serialize()
  73094. ], FollowCamera.prototype, "radius", void 0);
  73095. __decorate([
  73096. BABYLON.serialize()
  73097. ], FollowCamera.prototype, "rotationOffset", void 0);
  73098. __decorate([
  73099. BABYLON.serialize()
  73100. ], FollowCamera.prototype, "heightOffset", void 0);
  73101. __decorate([
  73102. BABYLON.serialize()
  73103. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73104. __decorate([
  73105. BABYLON.serialize()
  73106. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73107. __decorate([
  73108. BABYLON.serializeAsMeshReference("lockedTargetId")
  73109. ], FollowCamera.prototype, "lockedTarget", void 0);
  73110. return FollowCamera;
  73111. }(BABYLON.TargetCamera));
  73112. BABYLON.FollowCamera = FollowCamera;
  73113. var ArcFollowCamera = /** @class */ (function (_super) {
  73114. __extends(ArcFollowCamera, _super);
  73115. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73116. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73117. _this.alpha = alpha;
  73118. _this.beta = beta;
  73119. _this.radius = radius;
  73120. _this.target = target;
  73121. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73122. _this.follow();
  73123. return _this;
  73124. }
  73125. ArcFollowCamera.prototype.follow = function () {
  73126. if (!this.target) {
  73127. return;
  73128. }
  73129. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73130. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73131. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73132. var targetPosition = this.target.getAbsolutePosition();
  73133. this.position = targetPosition.add(this._cartesianCoordinates);
  73134. this.setTarget(targetPosition);
  73135. };
  73136. ArcFollowCamera.prototype._checkInputs = function () {
  73137. _super.prototype._checkInputs.call(this);
  73138. this.follow();
  73139. };
  73140. ArcFollowCamera.prototype.getClassName = function () {
  73141. return "ArcFollowCamera";
  73142. };
  73143. return ArcFollowCamera;
  73144. }(BABYLON.TargetCamera));
  73145. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73146. })(BABYLON || (BABYLON = {}));
  73147. //# sourceMappingURL=babylon.followCamera.js.map
  73148. var BABYLON;
  73149. (function (BABYLON) {
  73150. // We're mainly based on the logic defined into the FreeCamera code
  73151. var UniversalCamera = /** @class */ (function (_super) {
  73152. __extends(UniversalCamera, _super);
  73153. //-- end properties for backward compatibility for inputs
  73154. function UniversalCamera(name, position, scene) {
  73155. var _this = _super.call(this, name, position, scene) || this;
  73156. _this.inputs.addGamepad();
  73157. return _this;
  73158. }
  73159. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73160. //-- Begin properties for backward compatibility for inputs
  73161. get: function () {
  73162. var gamepad = this.inputs.attached["gamepad"];
  73163. if (gamepad)
  73164. return gamepad.gamepadAngularSensibility;
  73165. return 0;
  73166. },
  73167. set: function (value) {
  73168. var gamepad = this.inputs.attached["gamepad"];
  73169. if (gamepad)
  73170. gamepad.gamepadAngularSensibility = value;
  73171. },
  73172. enumerable: true,
  73173. configurable: true
  73174. });
  73175. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73176. get: function () {
  73177. var gamepad = this.inputs.attached["gamepad"];
  73178. if (gamepad)
  73179. return gamepad.gamepadMoveSensibility;
  73180. return 0;
  73181. },
  73182. set: function (value) {
  73183. var gamepad = this.inputs.attached["gamepad"];
  73184. if (gamepad)
  73185. gamepad.gamepadMoveSensibility = value;
  73186. },
  73187. enumerable: true,
  73188. configurable: true
  73189. });
  73190. UniversalCamera.prototype.getClassName = function () {
  73191. return "UniversalCamera";
  73192. };
  73193. return UniversalCamera;
  73194. }(BABYLON.TouchCamera));
  73195. BABYLON.UniversalCamera = UniversalCamera;
  73196. })(BABYLON || (BABYLON = {}));
  73197. //# sourceMappingURL=babylon.universalCamera.js.map
  73198. var BABYLON;
  73199. (function (BABYLON) {
  73200. // We're mainly based on the logic defined into the FreeCamera code
  73201. var GamepadCamera = /** @class */ (function (_super) {
  73202. __extends(GamepadCamera, _super);
  73203. //-- end properties for backward compatibility for inputs
  73204. function GamepadCamera(name, position, scene) {
  73205. return _super.call(this, name, position, scene) || this;
  73206. }
  73207. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73208. //-- Begin properties for backward compatibility for inputs
  73209. get: function () {
  73210. var gamepad = this.inputs.attached["gamepad"];
  73211. if (gamepad)
  73212. return gamepad.gamepadAngularSensibility;
  73213. return 0;
  73214. },
  73215. set: function (value) {
  73216. var gamepad = this.inputs.attached["gamepad"];
  73217. if (gamepad)
  73218. gamepad.gamepadAngularSensibility = value;
  73219. },
  73220. enumerable: true,
  73221. configurable: true
  73222. });
  73223. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73224. get: function () {
  73225. var gamepad = this.inputs.attached["gamepad"];
  73226. if (gamepad)
  73227. return gamepad.gamepadMoveSensibility;
  73228. return 0;
  73229. },
  73230. set: function (value) {
  73231. var gamepad = this.inputs.attached["gamepad"];
  73232. if (gamepad)
  73233. gamepad.gamepadMoveSensibility = value;
  73234. },
  73235. enumerable: true,
  73236. configurable: true
  73237. });
  73238. GamepadCamera.prototype.getClassName = function () {
  73239. return "GamepadCamera";
  73240. };
  73241. return GamepadCamera;
  73242. }(BABYLON.UniversalCamera));
  73243. BABYLON.GamepadCamera = GamepadCamera;
  73244. })(BABYLON || (BABYLON = {}));
  73245. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73246. var BABYLON;
  73247. (function (BABYLON) {
  73248. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73249. function PostProcessRenderPipelineManager() {
  73250. this._renderPipelines = {};
  73251. }
  73252. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73253. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73254. };
  73255. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73256. if (unique === void 0) { unique = false; }
  73257. var renderPipeline = this._renderPipelines[renderPipelineName];
  73258. if (!renderPipeline) {
  73259. return;
  73260. }
  73261. renderPipeline._attachCameras(cameras, unique);
  73262. };
  73263. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73264. var renderPipeline = this._renderPipelines[renderPipelineName];
  73265. if (!renderPipeline) {
  73266. return;
  73267. }
  73268. renderPipeline._detachCameras(cameras);
  73269. };
  73270. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73271. var renderPipeline = this._renderPipelines[renderPipelineName];
  73272. if (!renderPipeline) {
  73273. return;
  73274. }
  73275. renderPipeline._enableEffect(renderEffectName, cameras);
  73276. };
  73277. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73278. var renderPipeline = this._renderPipelines[renderPipelineName];
  73279. if (!renderPipeline) {
  73280. return;
  73281. }
  73282. renderPipeline._disableEffect(renderEffectName, cameras);
  73283. };
  73284. PostProcessRenderPipelineManager.prototype.update = function () {
  73285. for (var renderPipelineName in this._renderPipelines) {
  73286. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73287. var pipeline = this._renderPipelines[renderPipelineName];
  73288. if (!pipeline.isSupported) {
  73289. pipeline.dispose();
  73290. delete this._renderPipelines[renderPipelineName];
  73291. }
  73292. else {
  73293. pipeline._update();
  73294. }
  73295. }
  73296. }
  73297. };
  73298. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73299. for (var renderPipelineName in this._renderPipelines) {
  73300. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73301. var pipeline = this._renderPipelines[renderPipelineName];
  73302. pipeline._rebuild();
  73303. }
  73304. }
  73305. };
  73306. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73307. for (var renderPipelineName in this._renderPipelines) {
  73308. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73309. var pipeline = this._renderPipelines[renderPipelineName];
  73310. pipeline.dispose();
  73311. }
  73312. }
  73313. };
  73314. return PostProcessRenderPipelineManager;
  73315. }());
  73316. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73317. })(BABYLON || (BABYLON = {}));
  73318. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73319. var BABYLON;
  73320. (function (BABYLON) {
  73321. /**
  73322. * This represents a set of one or more post processes in Babylon.
  73323. * A post process can be used to apply a shader to a texture after it is rendered.
  73324. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73325. */
  73326. var PostProcessRenderEffect = /** @class */ (function () {
  73327. /**
  73328. * Instantiates a post process render effect.
  73329. * A post process can be used to apply a shader to a texture after it is rendered.
  73330. * @param engine The engine the effect is tied to
  73331. * @param name The name of the effect
  73332. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73333. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73334. */
  73335. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73336. this._name = name;
  73337. this._singleInstance = singleInstance || true;
  73338. this._getPostProcesses = getPostProcesses;
  73339. this._cameras = {};
  73340. this._indicesForCamera = {};
  73341. this._postProcesses = {};
  73342. }
  73343. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73344. /**
  73345. * Checks if all the post processes in the effect are supported.
  73346. */
  73347. get: function () {
  73348. for (var index in this._postProcesses) {
  73349. if (this._postProcesses.hasOwnProperty(index)) {
  73350. var pps = this._postProcesses[index];
  73351. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73352. if (!pps[ppIndex].isSupported) {
  73353. return false;
  73354. }
  73355. }
  73356. }
  73357. }
  73358. return true;
  73359. },
  73360. enumerable: true,
  73361. configurable: true
  73362. });
  73363. /**
  73364. * Updates the current state of the effect
  73365. */
  73366. PostProcessRenderEffect.prototype._update = function () {
  73367. };
  73368. /**
  73369. * Attaches the effect on cameras
  73370. * @param cameras The camera to attach to.
  73371. */
  73372. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73373. var _this = this;
  73374. var cameraKey;
  73375. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73376. if (!cams) {
  73377. return;
  73378. }
  73379. for (var i = 0; i < cams.length; i++) {
  73380. var camera = cams[i];
  73381. var cameraName = camera.name;
  73382. if (this._singleInstance) {
  73383. cameraKey = 0;
  73384. }
  73385. else {
  73386. cameraKey = cameraName;
  73387. }
  73388. if (!this._postProcesses[cameraKey]) {
  73389. var postProcess = this._getPostProcesses();
  73390. if (postProcess) {
  73391. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73392. }
  73393. }
  73394. if (!this._indicesForCamera[cameraName]) {
  73395. this._indicesForCamera[cameraName] = [];
  73396. }
  73397. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73398. var index = camera.attachPostProcess(postProcess);
  73399. _this._indicesForCamera[cameraName].push(index);
  73400. });
  73401. if (!this._cameras[cameraName]) {
  73402. this._cameras[cameraName] = camera;
  73403. }
  73404. }
  73405. };
  73406. /**
  73407. * Detatches the effect on cameras
  73408. * @param cameras The camera to detatch from.
  73409. */
  73410. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73411. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73412. if (!cams) {
  73413. return;
  73414. }
  73415. for (var i = 0; i < cams.length; i++) {
  73416. var camera = cams[i];
  73417. var cameraName = camera.name;
  73418. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73419. camera.detachPostProcess(postProcess);
  73420. });
  73421. if (this._cameras[cameraName]) {
  73422. //this._indicesForCamera.splice(index, 1);
  73423. this._cameras[cameraName] = null;
  73424. }
  73425. }
  73426. };
  73427. /**
  73428. * Enables the effect on given cameras
  73429. * @param cameras The camera to enable.
  73430. */
  73431. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73432. var _this = this;
  73433. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73434. if (!cams) {
  73435. return;
  73436. }
  73437. for (var i = 0; i < cams.length; i++) {
  73438. var camera = cams[i];
  73439. var cameraName = camera.name;
  73440. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73441. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73442. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73443. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73444. });
  73445. }
  73446. }
  73447. }
  73448. };
  73449. /**
  73450. * Disables the effect on the given cameras
  73451. * @param cameras The camera to disable.
  73452. */
  73453. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73454. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73455. if (!cams) {
  73456. return;
  73457. }
  73458. for (var i = 0; i < cams.length; i++) {
  73459. var camera = cams[i];
  73460. var cameraName = camera.name;
  73461. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73462. camera.detachPostProcess(postProcess);
  73463. });
  73464. }
  73465. };
  73466. /**
  73467. * Gets a list of the post processes contained in the effect.
  73468. * @param camera The camera to get the post processes on.
  73469. * @returns The list of the post processes in the effect.
  73470. */
  73471. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73472. if (this._singleInstance) {
  73473. return this._postProcesses[0];
  73474. }
  73475. else {
  73476. if (!camera) {
  73477. return null;
  73478. }
  73479. return this._postProcesses[camera.name];
  73480. }
  73481. };
  73482. return PostProcessRenderEffect;
  73483. }());
  73484. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73485. })(BABYLON || (BABYLON = {}));
  73486. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73487. var BABYLON;
  73488. (function (BABYLON) {
  73489. var PostProcessRenderPipeline = /** @class */ (function () {
  73490. function PostProcessRenderPipeline(engine, name) {
  73491. this.engine = engine;
  73492. this._name = name;
  73493. this._renderEffects = {};
  73494. this._renderEffectsForIsolatedPass = new Array();
  73495. this._cameras = [];
  73496. }
  73497. PostProcessRenderPipeline.prototype.getClassName = function () {
  73498. return "PostProcessRenderPipeline";
  73499. };
  73500. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73501. get: function () {
  73502. for (var renderEffectName in this._renderEffects) {
  73503. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73504. if (!this._renderEffects[renderEffectName].isSupported) {
  73505. return false;
  73506. }
  73507. }
  73508. }
  73509. return true;
  73510. },
  73511. enumerable: true,
  73512. configurable: true
  73513. });
  73514. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73515. this._renderEffects[renderEffect._name] = renderEffect;
  73516. };
  73517. // private
  73518. PostProcessRenderPipeline.prototype._rebuild = function () {
  73519. };
  73520. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73521. var renderEffects = this._renderEffects[renderEffectName];
  73522. if (!renderEffects) {
  73523. return;
  73524. }
  73525. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73526. };
  73527. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73528. var renderEffects = this._renderEffects[renderEffectName];
  73529. if (!renderEffects) {
  73530. return;
  73531. }
  73532. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73533. };
  73534. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73535. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73536. if (!cams) {
  73537. return;
  73538. }
  73539. var indicesToDelete = [];
  73540. var i;
  73541. for (i = 0; i < cams.length; i++) {
  73542. var camera = cams[i];
  73543. var cameraName = camera.name;
  73544. if (this._cameras.indexOf(camera) === -1) {
  73545. this._cameras[cameraName] = camera;
  73546. }
  73547. else if (unique) {
  73548. indicesToDelete.push(i);
  73549. }
  73550. }
  73551. for (i = 0; i < indicesToDelete.length; i++) {
  73552. cameras.splice(indicesToDelete[i], 1);
  73553. }
  73554. for (var renderEffectName in this._renderEffects) {
  73555. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73556. this._renderEffects[renderEffectName]._attachCameras(cams);
  73557. }
  73558. }
  73559. };
  73560. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73561. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73562. if (!cams) {
  73563. return;
  73564. }
  73565. for (var renderEffectName in this._renderEffects) {
  73566. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73567. this._renderEffects[renderEffectName]._detachCameras(cams);
  73568. }
  73569. }
  73570. for (var i = 0; i < cams.length; i++) {
  73571. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73572. }
  73573. };
  73574. PostProcessRenderPipeline.prototype._update = function () {
  73575. for (var renderEffectName in this._renderEffects) {
  73576. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73577. this._renderEffects[renderEffectName]._update();
  73578. }
  73579. }
  73580. for (var i = 0; i < this._cameras.length; i++) {
  73581. var cameraName = this._cameras[i].name;
  73582. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73583. this._renderEffectsForIsolatedPass[cameraName]._update();
  73584. }
  73585. }
  73586. };
  73587. PostProcessRenderPipeline.prototype._reset = function () {
  73588. this._renderEffects = {};
  73589. this._renderEffectsForIsolatedPass = new Array();
  73590. };
  73591. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73592. // 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)
  73593. var effectKeys = Object.keys(this._renderEffects);
  73594. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73595. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73596. if (postProcesses) {
  73597. postProcesses[0].samples = sampleCount;
  73598. return true;
  73599. }
  73600. }
  73601. return false;
  73602. };
  73603. PostProcessRenderPipeline.prototype.dispose = function () {
  73604. // Must be implemented by children
  73605. };
  73606. __decorate([
  73607. BABYLON.serialize()
  73608. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73609. return PostProcessRenderPipeline;
  73610. }());
  73611. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73612. })(BABYLON || (BABYLON = {}));
  73613. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73614. var BABYLON;
  73615. (function (BABYLON) {
  73616. /**
  73617. * This represents a depth renderer in Babylon.
  73618. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73619. */
  73620. var DepthRenderer = /** @class */ (function () {
  73621. /**
  73622. * Instantiates a depth renderer
  73623. * @param scene The scene the renderer belongs to
  73624. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73625. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73626. */
  73627. function DepthRenderer(scene, type, camera) {
  73628. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73629. if (camera === void 0) { camera = null; }
  73630. var _this = this;
  73631. this._scene = scene;
  73632. this._camera = camera;
  73633. var engine = scene.getEngine();
  73634. // Render target
  73635. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73636. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73637. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73638. this._depthMap.refreshRate = 1;
  73639. this._depthMap.renderParticles = false;
  73640. this._depthMap.renderList = null;
  73641. // Camera to get depth map from to support multiple concurrent cameras
  73642. this._depthMap.activeCamera = this._camera;
  73643. this._depthMap.ignoreCameraViewport = true;
  73644. this._depthMap.useCameraPostProcesses = false;
  73645. // set default depth value to 1.0 (far away)
  73646. this._depthMap.onClearObservable.add(function (engine) {
  73647. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73648. });
  73649. // Custom render function
  73650. var renderSubMesh = function (subMesh) {
  73651. var mesh = subMesh.getRenderingMesh();
  73652. var scene = _this._scene;
  73653. var engine = scene.getEngine();
  73654. var material = subMesh.getMaterial();
  73655. if (!material) {
  73656. return;
  73657. }
  73658. // Culling and reverse (right handed system)
  73659. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73660. // Managing instances
  73661. var batch = mesh._getInstancesRenderList(subMesh._id);
  73662. if (batch.mustReturn) {
  73663. return;
  73664. }
  73665. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73666. var camera = _this._camera || scene.activeCamera;
  73667. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73668. engine.enableEffect(_this._effect);
  73669. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73670. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73671. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73672. // Alpha test
  73673. if (material && material.needAlphaTesting()) {
  73674. var alphaTexture = material.getAlphaTestTexture();
  73675. if (alphaTexture) {
  73676. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73677. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73678. }
  73679. }
  73680. // Bones
  73681. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73682. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73683. }
  73684. // Draw
  73685. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73686. }
  73687. };
  73688. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73689. var index;
  73690. if (depthOnlySubMeshes.length) {
  73691. engine.setColorWrite(false);
  73692. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73693. renderSubMesh(depthOnlySubMeshes.data[index]);
  73694. }
  73695. engine.setColorWrite(true);
  73696. }
  73697. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73698. renderSubMesh(opaqueSubMeshes.data[index]);
  73699. }
  73700. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73701. renderSubMesh(alphaTestSubMeshes.data[index]);
  73702. }
  73703. };
  73704. }
  73705. /**
  73706. * Creates the depth rendering effect and checks if the effect is ready.
  73707. * @param subMesh The submesh to be used to render the depth map of
  73708. * @param useInstances If multiple world instances should be used
  73709. * @returns if the depth renderer is ready to render the depth map
  73710. */
  73711. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73712. var material = subMesh.getMaterial();
  73713. if (material.disableDepthWrite) {
  73714. return false;
  73715. }
  73716. var defines = [];
  73717. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73718. var mesh = subMesh.getMesh();
  73719. // Alpha test
  73720. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73721. defines.push("#define ALPHATEST");
  73722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73723. attribs.push(BABYLON.VertexBuffer.UVKind);
  73724. defines.push("#define UV1");
  73725. }
  73726. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73727. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73728. defines.push("#define UV2");
  73729. }
  73730. }
  73731. // Bones
  73732. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73735. if (mesh.numBoneInfluencers > 4) {
  73736. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73737. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73738. }
  73739. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73740. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73741. }
  73742. else {
  73743. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73744. }
  73745. // Instances
  73746. if (useInstances) {
  73747. defines.push("#define INSTANCES");
  73748. attribs.push("world0");
  73749. attribs.push("world1");
  73750. attribs.push("world2");
  73751. attribs.push("world3");
  73752. }
  73753. // Get correct effect
  73754. var join = defines.join("\n");
  73755. if (this._cachedDefines !== join) {
  73756. this._cachedDefines = join;
  73757. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73758. }
  73759. return this._effect.isReady();
  73760. };
  73761. /**
  73762. * Gets the texture which the depth map will be written to.
  73763. * @returns The depth map texture
  73764. */
  73765. DepthRenderer.prototype.getDepthMap = function () {
  73766. return this._depthMap;
  73767. };
  73768. /**
  73769. * Disposes of the depth renderer.
  73770. */
  73771. DepthRenderer.prototype.dispose = function () {
  73772. this._depthMap.dispose();
  73773. };
  73774. return DepthRenderer;
  73775. }());
  73776. BABYLON.DepthRenderer = DepthRenderer;
  73777. })(BABYLON || (BABYLON = {}));
  73778. //# sourceMappingURL=babylon.depthRenderer.js.map
  73779. var BABYLON;
  73780. (function (BABYLON) {
  73781. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73782. __extends(SSAORenderingPipeline, _super);
  73783. /**
  73784. * @constructor
  73785. * @param {string} name - The rendering pipeline name
  73786. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73787. * @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 }
  73788. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73789. */
  73790. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73791. var _this = _super.call(this, scene.getEngine(), name) || this;
  73792. // Members
  73793. /**
  73794. * The PassPostProcess id in the pipeline that contains the original scene color
  73795. */
  73796. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73797. /**
  73798. * The SSAO PostProcess id in the pipeline
  73799. */
  73800. _this.SSAORenderEffect = "SSAORenderEffect";
  73801. /**
  73802. * The horizontal blur PostProcess id in the pipeline
  73803. */
  73804. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73805. /**
  73806. * The vertical blur PostProcess id in the pipeline
  73807. */
  73808. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73809. /**
  73810. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73811. */
  73812. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73813. /**
  73814. * The output strength of the SSAO post-process. Default value is 1.0.
  73815. */
  73816. _this.totalStrength = 1.0;
  73817. /**
  73818. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73819. */
  73820. _this.radius = 0.0001;
  73821. /**
  73822. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73823. * Must not be equal to fallOff and superior to fallOff.
  73824. * Default value is 0.975
  73825. */
  73826. _this.area = 0.0075;
  73827. /**
  73828. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73829. * Must not be equal to area and inferior to area.
  73830. * Default value is 0.0
  73831. */
  73832. _this.fallOff = 0.000001;
  73833. /**
  73834. * The base color of the SSAO post-process
  73835. * The final result is "base + ssao" between [0, 1]
  73836. */
  73837. _this.base = 0.5;
  73838. _this._firstUpdate = true;
  73839. _this._scene = scene;
  73840. // Set up assets
  73841. _this._createRandomTexture();
  73842. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73843. var ssaoRatio = ratio.ssaoRatio || ratio;
  73844. var combineRatio = ratio.combineRatio || ratio;
  73845. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73846. _this._createSSAOPostProcess(ssaoRatio);
  73847. _this._createBlurPostProcess(ssaoRatio);
  73848. _this._createSSAOCombinePostProcess(combineRatio);
  73849. // Set up pipeline
  73850. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73851. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73852. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73853. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73854. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73855. // Finish
  73856. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73857. if (cameras)
  73858. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73859. return _this;
  73860. }
  73861. // Public Methods
  73862. /**
  73863. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73864. */
  73865. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73866. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73867. for (var i = 0; i < this._scene.cameras.length; i++) {
  73868. var camera = this._scene.cameras[i];
  73869. this._originalColorPostProcess.dispose(camera);
  73870. this._ssaoPostProcess.dispose(camera);
  73871. this._blurHPostProcess.dispose(camera);
  73872. this._blurVPostProcess.dispose(camera);
  73873. this._ssaoCombinePostProcess.dispose(camera);
  73874. }
  73875. this._randomTexture.dispose();
  73876. if (disableDepthRender)
  73877. this._scene.disableDepthRenderer();
  73878. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73879. _super.prototype.dispose.call(this);
  73880. };
  73881. // Private Methods
  73882. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73883. var _this = this;
  73884. var size = 16;
  73885. 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);
  73886. 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);
  73887. this._blurHPostProcess.onActivateObservable.add(function () {
  73888. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73889. _this._blurHPostProcess.kernel = size * dw;
  73890. });
  73891. this._blurVPostProcess.onActivateObservable.add(function () {
  73892. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73893. _this._blurVPostProcess.kernel = size * dw;
  73894. });
  73895. };
  73896. SSAORenderingPipeline.prototype._rebuild = function () {
  73897. this._firstUpdate = true;
  73898. _super.prototype._rebuild.call(this);
  73899. };
  73900. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73901. var _this = this;
  73902. var numSamples = 16;
  73903. var sampleSphere = [
  73904. 0.5381, 0.1856, -0.4319,
  73905. 0.1379, 0.2486, 0.4430,
  73906. 0.3371, 0.5679, -0.0057,
  73907. -0.6999, -0.0451, -0.0019,
  73908. 0.0689, -0.1598, -0.8547,
  73909. 0.0560, 0.0069, -0.1843,
  73910. -0.0146, 0.1402, 0.0762,
  73911. 0.0100, -0.1924, -0.0344,
  73912. -0.3577, -0.5301, -0.4358,
  73913. -0.3169, 0.1063, 0.0158,
  73914. 0.0103, -0.5869, 0.0046,
  73915. -0.0897, -0.4940, 0.3287,
  73916. 0.7119, -0.0154, -0.0918,
  73917. -0.0533, 0.0596, -0.5411,
  73918. 0.0352, -0.0631, 0.5460,
  73919. -0.4776, 0.2847, -0.0271
  73920. ];
  73921. var samplesFactor = 1.0 / numSamples;
  73922. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73923. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73924. "area", "fallOff", "base", "range", "viewport"
  73925. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73926. this._ssaoPostProcess.onApply = function (effect) {
  73927. if (_this._firstUpdate) {
  73928. effect.setArray3("sampleSphere", sampleSphere);
  73929. effect.setFloat("samplesFactor", samplesFactor);
  73930. effect.setFloat("randTextureTiles", 4.0);
  73931. }
  73932. effect.setFloat("totalStrength", _this.totalStrength);
  73933. effect.setFloat("radius", _this.radius);
  73934. effect.setFloat("area", _this.area);
  73935. effect.setFloat("fallOff", _this.fallOff);
  73936. effect.setFloat("base", _this.base);
  73937. effect.setTexture("textureSampler", _this._depthTexture);
  73938. effect.setTexture("randomSampler", _this._randomTexture);
  73939. };
  73940. };
  73941. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73942. var _this = this;
  73943. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73944. this._ssaoCombinePostProcess.onApply = function (effect) {
  73945. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73946. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73947. };
  73948. };
  73949. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73950. var size = 512;
  73951. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73952. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73953. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73954. var context = this._randomTexture.getContext();
  73955. var rand = function (min, max) {
  73956. return Math.random() * (max - min) + min;
  73957. };
  73958. var randVector = BABYLON.Vector3.Zero();
  73959. for (var x = 0; x < size; x++) {
  73960. for (var y = 0; y < size; y++) {
  73961. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73962. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73963. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73964. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73965. context.fillRect(x, y, 1, 1);
  73966. }
  73967. }
  73968. this._randomTexture.update(false);
  73969. };
  73970. __decorate([
  73971. BABYLON.serialize()
  73972. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73973. __decorate([
  73974. BABYLON.serialize()
  73975. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73976. __decorate([
  73977. BABYLON.serialize()
  73978. ], SSAORenderingPipeline.prototype, "area", void 0);
  73979. __decorate([
  73980. BABYLON.serialize()
  73981. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73982. __decorate([
  73983. BABYLON.serialize()
  73984. ], SSAORenderingPipeline.prototype, "base", void 0);
  73985. return SSAORenderingPipeline;
  73986. }(BABYLON.PostProcessRenderPipeline));
  73987. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73988. })(BABYLON || (BABYLON = {}));
  73989. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73990. var BABYLON;
  73991. (function (BABYLON) {
  73992. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73993. __extends(SSAO2RenderingPipeline, _super);
  73994. /**
  73995. * @constructor
  73996. * @param {string} name - The rendering pipeline name
  73997. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73998. * @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 }
  73999. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74000. */
  74001. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74002. var _this = _super.call(this, scene.getEngine(), name) || this;
  74003. // Members
  74004. /**
  74005. * The PassPostProcess id in the pipeline that contains the original scene color
  74006. */
  74007. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74008. /**
  74009. * The SSAO PostProcess id in the pipeline
  74010. */
  74011. _this.SSAORenderEffect = "SSAORenderEffect";
  74012. /**
  74013. * The horizontal blur PostProcess id in the pipeline
  74014. */
  74015. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74016. /**
  74017. * The vertical blur PostProcess id in the pipeline
  74018. */
  74019. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74020. /**
  74021. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74022. */
  74023. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74024. /**
  74025. * The output strength of the SSAO post-process. Default value is 1.0.
  74026. */
  74027. _this.totalStrength = 1.0;
  74028. /**
  74029. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74030. */
  74031. _this.maxZ = 100.0;
  74032. /**
  74033. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74034. */
  74035. _this.minZAspect = 0.2;
  74036. /**
  74037. * Number of samples used for the SSAO calculations. Default value is 8
  74038. */
  74039. _this._samples = 8;
  74040. /**
  74041. * Are we using bilateral blur ?
  74042. */
  74043. _this._expensiveBlur = true;
  74044. /**
  74045. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74046. */
  74047. _this.radius = 2.0;
  74048. /**
  74049. * The base color of the SSAO post-process
  74050. * The final result is "base + ssao" between [0, 1]
  74051. */
  74052. _this.base = 0.1;
  74053. _this._firstUpdate = true;
  74054. _this._scene = scene;
  74055. _this._ratio = ratio;
  74056. if (!_this.isSupported) {
  74057. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74058. return _this;
  74059. }
  74060. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74061. var blurRatio = _this._ratio.blurRatio || ratio;
  74062. // Set up assets
  74063. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74064. _this._createRandomTexture();
  74065. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74066. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74067. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74068. _this._createSSAOPostProcess(1.0);
  74069. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74070. _this._createSSAOCombinePostProcess(blurRatio);
  74071. // Set up pipeline
  74072. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74073. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74074. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74075. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74076. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74077. // Finish
  74078. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74079. if (cameras)
  74080. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74081. return _this;
  74082. }
  74083. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74084. get: function () {
  74085. return this._samples;
  74086. },
  74087. set: function (n) {
  74088. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74089. this._samples = n;
  74090. this._sampleSphere = this._generateHemisphere();
  74091. this._firstUpdate = true;
  74092. },
  74093. enumerable: true,
  74094. configurable: true
  74095. });
  74096. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74097. get: function () {
  74098. return this._expensiveBlur;
  74099. },
  74100. set: function (b) {
  74101. 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"]);
  74102. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74103. this._expensiveBlur = b;
  74104. this._firstUpdate = true;
  74105. },
  74106. enumerable: true,
  74107. configurable: true
  74108. });
  74109. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74110. /**
  74111. * Support test.
  74112. */
  74113. get: function () {
  74114. var engine = BABYLON.Engine.LastCreatedEngine;
  74115. if (!engine) {
  74116. return false;
  74117. }
  74118. return engine.getCaps().drawBuffersExtension;
  74119. },
  74120. enumerable: true,
  74121. configurable: true
  74122. });
  74123. // Public Methods
  74124. /**
  74125. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74126. */
  74127. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74128. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74129. for (var i = 0; i < this._scene.cameras.length; i++) {
  74130. var camera = this._scene.cameras[i];
  74131. this._originalColorPostProcess.dispose(camera);
  74132. this._ssaoPostProcess.dispose(camera);
  74133. this._blurHPostProcess.dispose(camera);
  74134. this._blurVPostProcess.dispose(camera);
  74135. this._ssaoCombinePostProcess.dispose(camera);
  74136. }
  74137. this._randomTexture.dispose();
  74138. if (disableGeometryBufferRenderer)
  74139. this._scene.disableGeometryBufferRenderer();
  74140. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74141. _super.prototype.dispose.call(this);
  74142. };
  74143. // Private Methods
  74144. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74145. var _this = this;
  74146. this._samplerOffsets = [];
  74147. var expensive = this.expensiveBlur;
  74148. for (var i = -8; i < 8; i++) {
  74149. this._samplerOffsets.push(i * 2 + 0.5);
  74150. }
  74151. 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");
  74152. this._blurHPostProcess.onApply = function (effect) {
  74153. if (!_this._scene.activeCamera) {
  74154. return;
  74155. }
  74156. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74157. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74158. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74159. effect.setFloat("radius", _this.radius);
  74160. effect.setTexture("depthSampler", _this._depthTexture);
  74161. if (_this._firstUpdate) {
  74162. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74163. }
  74164. };
  74165. 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");
  74166. this._blurVPostProcess.onApply = function (effect) {
  74167. if (!_this._scene.activeCamera) {
  74168. return;
  74169. }
  74170. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74171. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74172. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74173. effect.setFloat("radius", _this.radius);
  74174. effect.setTexture("depthSampler", _this._depthTexture);
  74175. if (_this._firstUpdate) {
  74176. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74177. _this._firstUpdate = false;
  74178. }
  74179. };
  74180. };
  74181. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74182. this._firstUpdate = true;
  74183. _super.prototype._rebuild.call(this);
  74184. };
  74185. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74186. var numSamples = this.samples;
  74187. var result = [];
  74188. var vector, scale;
  74189. var rand = function (min, max) {
  74190. return Math.random() * (max - min) + min;
  74191. };
  74192. var i = 0;
  74193. while (i < numSamples) {
  74194. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74195. vector.normalize();
  74196. scale = i / numSamples;
  74197. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74198. vector.scaleInPlace(scale);
  74199. result.push(vector.x, vector.y, vector.z);
  74200. i++;
  74201. }
  74202. return result;
  74203. };
  74204. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74205. var _this = this;
  74206. var numSamples = this.samples;
  74207. this._sampleSphere = this._generateHemisphere();
  74208. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74209. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74210. "base", "range", "projection", "near", "far", "texelSize",
  74211. "xViewport", "yViewport", "maxZ", "minZAspect"
  74212. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74213. this._ssaoPostProcess.onApply = function (effect) {
  74214. if (_this._firstUpdate) {
  74215. effect.setArray3("sampleSphere", _this._sampleSphere);
  74216. effect.setFloat("randTextureTiles", 4.0);
  74217. }
  74218. if (!_this._scene.activeCamera) {
  74219. return;
  74220. }
  74221. effect.setFloat("samplesFactor", 1 / _this.samples);
  74222. effect.setFloat("totalStrength", _this.totalStrength);
  74223. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74224. effect.setFloat("radius", _this.radius);
  74225. effect.setFloat("maxZ", _this.maxZ);
  74226. effect.setFloat("minZAspect", _this.minZAspect);
  74227. effect.setFloat("base", _this.base);
  74228. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74229. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74230. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74231. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74232. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74233. effect.setTexture("textureSampler", _this._depthTexture);
  74234. effect.setTexture("normalSampler", _this._normalTexture);
  74235. effect.setTexture("randomSampler", _this._randomTexture);
  74236. };
  74237. };
  74238. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74239. var _this = this;
  74240. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74241. this._ssaoCombinePostProcess.onApply = function (effect) {
  74242. var viewport = _this._scene.activeCamera.viewport;
  74243. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74244. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74245. };
  74246. };
  74247. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74248. var size = 512;
  74249. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74250. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74251. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74252. var context = this._randomTexture.getContext();
  74253. var rand = function (min, max) {
  74254. return Math.random() * (max - min) + min;
  74255. };
  74256. var randVector = BABYLON.Vector3.Zero();
  74257. for (var x = 0; x < size; x++) {
  74258. for (var y = 0; y < size; y++) {
  74259. randVector.x = rand(0.0, 1.0);
  74260. randVector.y = rand(0.0, 1.0);
  74261. randVector.z = 0.0;
  74262. randVector.normalize();
  74263. randVector.scaleInPlace(255);
  74264. randVector.x = Math.floor(randVector.x);
  74265. randVector.y = Math.floor(randVector.y);
  74266. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74267. context.fillRect(x, y, 1, 1);
  74268. }
  74269. }
  74270. this._randomTexture.update(false);
  74271. };
  74272. /**
  74273. * Serialize the rendering pipeline (Used when exporting)
  74274. * @returns the serialized object
  74275. */
  74276. SSAO2RenderingPipeline.prototype.serialize = function () {
  74277. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74278. serializationObject.customType = "SSAO2RenderingPipeline";
  74279. return serializationObject;
  74280. };
  74281. /**
  74282. * Parse the serialized pipeline
  74283. * @param source Source pipeline.
  74284. * @param scene The scene to load the pipeline to.
  74285. * @param rootUrl The URL of the serialized pipeline.
  74286. * @returns An instantiated pipeline from the serialized object.
  74287. */
  74288. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74289. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74290. };
  74291. __decorate([
  74292. BABYLON.serialize()
  74293. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74294. __decorate([
  74295. BABYLON.serialize()
  74296. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74297. __decorate([
  74298. BABYLON.serialize()
  74299. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74300. __decorate([
  74301. BABYLON.serialize("samples")
  74302. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74303. __decorate([
  74304. BABYLON.serialize()
  74305. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74306. __decorate([
  74307. BABYLON.serialize("expensiveBlur")
  74308. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74309. __decorate([
  74310. BABYLON.serialize()
  74311. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74312. __decorate([
  74313. BABYLON.serialize()
  74314. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74315. return SSAO2RenderingPipeline;
  74316. }(BABYLON.PostProcessRenderPipeline));
  74317. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74318. })(BABYLON || (BABYLON = {}));
  74319. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74320. // BABYLON.JS Chromatic Aberration GLSL Shader
  74321. // Author: Olivier Guyot
  74322. // Separates very slightly R, G and B colors on the edges of the screen
  74323. // Inspired by Francois Tarlier & Martins Upitis
  74324. var BABYLON;
  74325. (function (BABYLON) {
  74326. var LensRenderingPipeline = /** @class */ (function (_super) {
  74327. __extends(LensRenderingPipeline, _super);
  74328. /**
  74329. * @constructor
  74330. *
  74331. * Effect parameters are as follow:
  74332. * {
  74333. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74334. * edge_blur: number; // from 0 to x (1 for realism)
  74335. * distortion: number; // from 0 to x (1 for realism)
  74336. * grain_amount: number; // from 0 to 1
  74337. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74338. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74339. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74340. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74341. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74342. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74343. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74344. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74345. * }
  74346. * Note: if an effect parameter is unset, effect is disabled
  74347. *
  74348. * @param {string} name - The rendering pipeline name
  74349. * @param {object} parameters - An object containing all parameters (see above)
  74350. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74351. * @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)
  74352. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74353. */
  74354. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74355. if (ratio === void 0) { ratio = 1.0; }
  74356. var _this = _super.call(this, scene.getEngine(), name) || this;
  74357. // Lens effects can be of the following:
  74358. // - chromatic aberration (slight shift of RGB colors)
  74359. // - blur on the edge of the lens
  74360. // - lens distortion
  74361. // - depth-of-field blur & highlights enhancing
  74362. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74363. // - grain effect (noise or custom texture)
  74364. // Two additional texture samplers are needed:
  74365. // - depth map (for depth-of-field)
  74366. // - grain texture
  74367. /**
  74368. * The chromatic aberration PostProcess id in the pipeline
  74369. */
  74370. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74371. /**
  74372. * The highlights enhancing PostProcess id in the pipeline
  74373. */
  74374. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74375. /**
  74376. * The depth-of-field PostProcess id in the pipeline
  74377. */
  74378. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74379. _this._scene = scene;
  74380. // Fetch texture samplers
  74381. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74382. if (parameters.grain_texture) {
  74383. _this._grainTexture = parameters.grain_texture;
  74384. }
  74385. else {
  74386. _this._createGrainTexture();
  74387. }
  74388. // save parameters
  74389. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74390. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74391. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74392. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74393. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74394. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74395. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74396. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74397. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74398. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74399. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74400. // Create effects
  74401. _this._createChromaticAberrationPostProcess(ratio);
  74402. _this._createHighlightsPostProcess(ratio);
  74403. _this._createDepthOfFieldPostProcess(ratio / 4);
  74404. // Set up pipeline
  74405. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74406. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74407. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74408. if (_this._highlightsGain === -1) {
  74409. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74410. }
  74411. // Finish
  74412. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74413. if (cameras) {
  74414. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74415. }
  74416. return _this;
  74417. }
  74418. // public methods (self explanatory)
  74419. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74420. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74421. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74422. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74423. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74424. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74425. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74426. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74427. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74428. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74429. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74430. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74431. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74432. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74433. };
  74434. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74435. this._highlightsPostProcess.updateEffect();
  74436. };
  74437. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74438. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74439. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74440. this._highlightsGain = amount;
  74441. };
  74442. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74443. if (this._highlightsGain === -1) {
  74444. this._highlightsGain = 1.0;
  74445. }
  74446. this._highlightsThreshold = amount;
  74447. };
  74448. LensRenderingPipeline.prototype.disableHighlights = function () {
  74449. this._highlightsGain = -1;
  74450. };
  74451. /**
  74452. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74453. */
  74454. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74455. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74456. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74457. this._chromaticAberrationPostProcess = null;
  74458. this._highlightsPostProcess = null;
  74459. this._depthOfFieldPostProcess = null;
  74460. this._grainTexture.dispose();
  74461. if (disableDepthRender)
  74462. this._scene.disableDepthRenderer();
  74463. };
  74464. // colors shifting and distortion
  74465. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74466. var _this = this;
  74467. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74468. [], // samplers
  74469. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74470. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74471. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74472. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74473. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74474. effect.setFloat('radialIntensity', 1);
  74475. effect.setFloat2('direction', 17, 17);
  74476. effect.setFloat2('centerPosition', 0.5, 0.5);
  74477. };
  74478. };
  74479. // highlights enhancing
  74480. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74481. var _this = this;
  74482. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74483. [], // samplers
  74484. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74485. this._highlightsPostProcess.onApply = function (effect) {
  74486. effect.setFloat('gain', _this._highlightsGain);
  74487. effect.setFloat('threshold', _this._highlightsThreshold);
  74488. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74489. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74490. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74491. };
  74492. };
  74493. // colors shifting and distortion
  74494. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74495. var _this = this;
  74496. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74497. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74498. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74499. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74500. this._depthOfFieldPostProcess.onApply = function (effect) {
  74501. effect.setTexture("depthSampler", _this._depthTexture);
  74502. effect.setTexture("grainSampler", _this._grainTexture);
  74503. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74504. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74505. effect.setFloat('grain_amount', _this._grainAmount);
  74506. effect.setBool('blur_noise', _this._blurNoise);
  74507. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74508. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74509. effect.setFloat('distortion', _this._distortion);
  74510. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74511. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74512. effect.setFloat('aperture', _this._dofAperture);
  74513. effect.setFloat('darken', _this._dofDarken);
  74514. effect.setFloat('edge_blur', _this._edgeBlur);
  74515. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74516. if (_this._scene.activeCamera) {
  74517. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74518. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74519. }
  74520. };
  74521. };
  74522. // creates a black and white random noise texture, 512x512
  74523. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74524. var size = 512;
  74525. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74526. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74527. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74528. var context = this._grainTexture.getContext();
  74529. var rand = function (min, max) {
  74530. return Math.random() * (max - min) + min;
  74531. };
  74532. var value;
  74533. for (var x = 0; x < size; x++) {
  74534. for (var y = 0; y < size; y++) {
  74535. value = Math.floor(rand(0.42, 0.58) * 255);
  74536. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74537. context.fillRect(x, y, 1, 1);
  74538. }
  74539. }
  74540. this._grainTexture.update(false);
  74541. };
  74542. return LensRenderingPipeline;
  74543. }(BABYLON.PostProcessRenderPipeline));
  74544. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74545. })(BABYLON || (BABYLON = {}));
  74546. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74547. var BABYLON;
  74548. (function (BABYLON) {
  74549. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74550. __extends(StandardRenderingPipeline, _super);
  74551. /**
  74552. * @constructor
  74553. * @param {string} name - The rendering pipeline name
  74554. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74555. * @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)
  74556. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74557. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74558. */
  74559. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74560. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74561. var _this = _super.call(this, scene.getEngine(), name) || this;
  74562. _this.downSampleX4PostProcess = null;
  74563. _this.brightPassPostProcess = null;
  74564. _this.blurHPostProcesses = [];
  74565. _this.blurVPostProcesses = [];
  74566. _this.textureAdderPostProcess = null;
  74567. _this.volumetricLightPostProcess = null;
  74568. _this.volumetricLightSmoothXPostProcess = null;
  74569. _this.volumetricLightSmoothYPostProcess = null;
  74570. _this.volumetricLightMergePostProces = null;
  74571. _this.volumetricLightFinalPostProcess = null;
  74572. _this.luminancePostProcess = null;
  74573. _this.luminanceDownSamplePostProcesses = [];
  74574. _this.hdrPostProcess = null;
  74575. _this.textureAdderFinalPostProcess = null;
  74576. _this.lensFlareFinalPostProcess = null;
  74577. _this.hdrFinalPostProcess = null;
  74578. _this.lensFlarePostProcess = null;
  74579. _this.lensFlareComposePostProcess = null;
  74580. _this.motionBlurPostProcess = null;
  74581. _this.depthOfFieldPostProcess = null;
  74582. // Values
  74583. _this.brightThreshold = 1.0;
  74584. _this.blurWidth = 512.0;
  74585. _this.horizontalBlur = false;
  74586. _this.exposure = 1.0;
  74587. _this.lensTexture = null;
  74588. _this.volumetricLightCoefficient = 0.2;
  74589. _this.volumetricLightPower = 4.0;
  74590. _this.volumetricLightBlurScale = 64.0;
  74591. _this.sourceLight = null;
  74592. _this.hdrMinimumLuminance = 1.0;
  74593. _this.hdrDecreaseRate = 0.5;
  74594. _this.hdrIncreaseRate = 0.5;
  74595. _this.lensColorTexture = null;
  74596. _this.lensFlareStrength = 20.0;
  74597. _this.lensFlareGhostDispersal = 1.4;
  74598. _this.lensFlareHaloWidth = 0.7;
  74599. _this.lensFlareDistortionStrength = 16.0;
  74600. _this.lensStarTexture = null;
  74601. _this.lensFlareDirtTexture = null;
  74602. _this.depthOfFieldDistance = 10.0;
  74603. _this.depthOfFieldBlurWidth = 64.0;
  74604. _this.motionStrength = 1.0;
  74605. // IAnimatable
  74606. _this.animations = [];
  74607. _this._currentDepthOfFieldSource = null;
  74608. _this._hdrCurrentLuminance = 1.0;
  74609. // Getters and setters
  74610. _this._bloomEnabled = true;
  74611. _this._depthOfFieldEnabled = false;
  74612. _this._vlsEnabled = false;
  74613. _this._lensFlareEnabled = false;
  74614. _this._hdrEnabled = false;
  74615. _this._motionBlurEnabled = false;
  74616. _this._motionBlurSamples = 64.0;
  74617. _this._volumetricLightStepsCount = 50.0;
  74618. _this._cameras = cameras || [];
  74619. // Initialize
  74620. _this._scene = scene;
  74621. _this._basePostProcess = originalPostProcess;
  74622. _this._ratio = ratio;
  74623. // Misc
  74624. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74625. // Finish
  74626. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74627. _this._buildPipeline();
  74628. return _this;
  74629. }
  74630. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74631. get: function () {
  74632. return this._bloomEnabled;
  74633. },
  74634. set: function (enabled) {
  74635. if (this._bloomEnabled === enabled) {
  74636. return;
  74637. }
  74638. this._bloomEnabled = enabled;
  74639. this._buildPipeline();
  74640. },
  74641. enumerable: true,
  74642. configurable: true
  74643. });
  74644. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74645. get: function () {
  74646. return this._depthOfFieldEnabled;
  74647. },
  74648. set: function (enabled) {
  74649. if (this._depthOfFieldEnabled === enabled) {
  74650. return;
  74651. }
  74652. this._depthOfFieldEnabled = enabled;
  74653. this._buildPipeline();
  74654. },
  74655. enumerable: true,
  74656. configurable: true
  74657. });
  74658. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74659. get: function () {
  74660. return this._lensFlareEnabled;
  74661. },
  74662. set: function (enabled) {
  74663. if (this._lensFlareEnabled === enabled) {
  74664. return;
  74665. }
  74666. this._lensFlareEnabled = enabled;
  74667. this._buildPipeline();
  74668. },
  74669. enumerable: true,
  74670. configurable: true
  74671. });
  74672. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74673. get: function () {
  74674. return this._hdrEnabled;
  74675. },
  74676. set: function (enabled) {
  74677. if (this._hdrEnabled === enabled) {
  74678. return;
  74679. }
  74680. this._hdrEnabled = enabled;
  74681. this._buildPipeline();
  74682. },
  74683. enumerable: true,
  74684. configurable: true
  74685. });
  74686. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74687. get: function () {
  74688. return this._vlsEnabled;
  74689. },
  74690. set: function (enabled) {
  74691. if (this._vlsEnabled === enabled) {
  74692. return;
  74693. }
  74694. if (enabled) {
  74695. var geometry = this._scene.enableGeometryBufferRenderer();
  74696. if (!geometry) {
  74697. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74698. return;
  74699. }
  74700. }
  74701. this._vlsEnabled = enabled;
  74702. this._buildPipeline();
  74703. },
  74704. enumerable: true,
  74705. configurable: true
  74706. });
  74707. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74708. get: function () {
  74709. return this._motionBlurEnabled;
  74710. },
  74711. set: function (enabled) {
  74712. if (this._motionBlurEnabled === enabled) {
  74713. return;
  74714. }
  74715. this._motionBlurEnabled = enabled;
  74716. this._buildPipeline();
  74717. },
  74718. enumerable: true,
  74719. configurable: true
  74720. });
  74721. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74722. get: function () {
  74723. return this._volumetricLightStepsCount;
  74724. },
  74725. set: function (count) {
  74726. if (this.volumetricLightPostProcess) {
  74727. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74728. }
  74729. this._volumetricLightStepsCount = count;
  74730. },
  74731. enumerable: true,
  74732. configurable: true
  74733. });
  74734. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74735. get: function () {
  74736. return this._motionBlurSamples;
  74737. },
  74738. set: function (samples) {
  74739. if (this.motionBlurPostProcess) {
  74740. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74741. }
  74742. this._motionBlurSamples = samples;
  74743. },
  74744. enumerable: true,
  74745. configurable: true
  74746. });
  74747. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74748. var _this = this;
  74749. var ratio = this._ratio;
  74750. var scene = this._scene;
  74751. this._disposePostProcesses();
  74752. this._reset();
  74753. // Create pass post-process
  74754. if (!this._basePostProcess) {
  74755. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74756. this.originalPostProcess.onApply = function (effect) {
  74757. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74758. };
  74759. }
  74760. else {
  74761. this.originalPostProcess = this._basePostProcess;
  74762. }
  74763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74764. this._currentDepthOfFieldSource = this.originalPostProcess;
  74765. if (this._bloomEnabled) {
  74766. // Create down sample X4 post-process
  74767. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74768. // Create bright pass post-process
  74769. this._createBrightPassPostProcess(scene, ratio / 2);
  74770. // Create gaussian blur post-processes (down sampling blurs)
  74771. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74772. // Create texture adder post-process
  74773. this._createTextureAdderPostProcess(scene, ratio);
  74774. // Create depth-of-field source post-process
  74775. 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);
  74776. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74777. }
  74778. if (this._vlsEnabled) {
  74779. // Create volumetric light
  74780. this._createVolumetricLightPostProcess(scene, ratio);
  74781. // Create volumetric light final post-process
  74782. 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);
  74783. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74784. }
  74785. if (this._lensFlareEnabled) {
  74786. // Create lens flare post-process
  74787. this._createLensFlarePostProcess(scene, ratio);
  74788. // Create depth-of-field source post-process post lens-flare and disable it now
  74789. 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);
  74790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74791. }
  74792. if (this._hdrEnabled) {
  74793. // Create luminance
  74794. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74795. // Create HDR
  74796. this._createHdrPostProcess(scene, ratio);
  74797. // Create depth-of-field source post-process post hdr and disable it now
  74798. 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);
  74799. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74800. }
  74801. if (this._depthOfFieldEnabled) {
  74802. // Create gaussian blur used by depth-of-field
  74803. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74804. // Create depth-of-field post-process
  74805. this._createDepthOfFieldPostProcess(scene, ratio);
  74806. }
  74807. if (this._motionBlurEnabled) {
  74808. // Create motion blur post-process
  74809. this._createMotionBlurPostProcess(scene, ratio);
  74810. }
  74811. if (this._cameras !== null) {
  74812. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74813. }
  74814. };
  74815. // Down Sample X4 Post-Processs
  74816. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74817. var _this = this;
  74818. var downSampleX4Offsets = new Array(32);
  74819. 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);
  74820. this.downSampleX4PostProcess.onApply = function (effect) {
  74821. var id = 0;
  74822. var width = _this.downSampleX4PostProcess.width;
  74823. var height = _this.downSampleX4PostProcess.height;
  74824. for (var i = -2; i < 2; i++) {
  74825. for (var j = -2; j < 2; j++) {
  74826. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74827. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74828. id += 2;
  74829. }
  74830. }
  74831. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74832. };
  74833. // Add to pipeline
  74834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74835. };
  74836. // Brightpass Post-Process
  74837. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74838. var _this = this;
  74839. var brightOffsets = new Array(8);
  74840. 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);
  74841. this.brightPassPostProcess.onApply = function (effect) {
  74842. var sU = (1.0 / _this.brightPassPostProcess.width);
  74843. var sV = (1.0 / _this.brightPassPostProcess.height);
  74844. brightOffsets[0] = -0.5 * sU;
  74845. brightOffsets[1] = 0.5 * sV;
  74846. brightOffsets[2] = 0.5 * sU;
  74847. brightOffsets[3] = 0.5 * sV;
  74848. brightOffsets[4] = -0.5 * sU;
  74849. brightOffsets[5] = -0.5 * sV;
  74850. brightOffsets[6] = 0.5 * sU;
  74851. brightOffsets[7] = -0.5 * sV;
  74852. effect.setArray2("dsOffsets", brightOffsets);
  74853. effect.setFloat("brightThreshold", _this.brightThreshold);
  74854. };
  74855. // Add to pipeline
  74856. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74857. };
  74858. // Create blur H&V post-processes
  74859. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74860. var _this = this;
  74861. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74862. var engine = scene.getEngine();
  74863. 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);
  74864. 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);
  74865. blurX.onActivateObservable.add(function () {
  74866. var dw = blurX.width / engine.getRenderWidth();
  74867. blurX.kernel = _this[blurWidthKey] * dw;
  74868. });
  74869. blurY.onActivateObservable.add(function () {
  74870. var dw = blurY.height / engine.getRenderHeight();
  74871. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74872. });
  74873. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74874. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74875. this.blurHPostProcesses.push(blurX);
  74876. this.blurVPostProcesses.push(blurY);
  74877. };
  74878. // Create texture adder post-process
  74879. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74880. var _this = this;
  74881. 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);
  74882. this.textureAdderPostProcess.onApply = function (effect) {
  74883. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74884. effect.setTexture("lensSampler", _this.lensTexture);
  74885. effect.setFloat("exposure", _this.exposure);
  74886. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74887. };
  74888. // Add to pipeline
  74889. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74890. };
  74891. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74892. var _this = this;
  74893. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74894. geometryRenderer.enablePosition = true;
  74895. var geometry = geometryRenderer.getGBuffer();
  74896. // Base post-process
  74897. 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));
  74898. var depthValues = BABYLON.Vector2.Zero();
  74899. this.volumetricLightPostProcess.onApply = function (effect) {
  74900. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74901. var generator = _this.sourceLight.getShadowGenerator();
  74902. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74903. effect.setTexture("positionSampler", geometry.textures[2]);
  74904. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74905. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74906. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74907. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74908. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74909. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74910. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74911. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74912. effect.setVector2("depthValues", depthValues);
  74913. }
  74914. };
  74915. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74916. // Smooth
  74917. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74918. // Merge
  74919. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74920. this.volumetricLightMergePostProces.onApply = function (effect) {
  74921. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74922. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74923. };
  74924. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74925. };
  74926. // Create luminance
  74927. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74928. var _this = this;
  74929. // Create luminance
  74930. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74931. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74932. var offsets = [];
  74933. this.luminancePostProcess.onApply = function (effect) {
  74934. var sU = (1.0 / _this.luminancePostProcess.width);
  74935. var sV = (1.0 / _this.luminancePostProcess.height);
  74936. offsets[0] = -0.5 * sU;
  74937. offsets[1] = 0.5 * sV;
  74938. offsets[2] = 0.5 * sU;
  74939. offsets[3] = 0.5 * sV;
  74940. offsets[4] = -0.5 * sU;
  74941. offsets[5] = -0.5 * sV;
  74942. offsets[6] = 0.5 * sU;
  74943. offsets[7] = -0.5 * sV;
  74944. effect.setArray2("lumOffsets", offsets);
  74945. };
  74946. // Add to pipeline
  74947. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74948. // Create down sample luminance
  74949. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74950. var size = Math.pow(3, i);
  74951. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74952. if (i === 0) {
  74953. defines += "#define FINAL_DOWN_SAMPLER";
  74954. }
  74955. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74956. this.luminanceDownSamplePostProcesses.push(postProcess);
  74957. }
  74958. // Create callbacks and add effects
  74959. var lastLuminance = this.luminancePostProcess;
  74960. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74961. var downSampleOffsets = new Array(18);
  74962. pp.onApply = function (effect) {
  74963. if (!lastLuminance) {
  74964. return;
  74965. }
  74966. var id = 0;
  74967. for (var x = -1; x < 2; x++) {
  74968. for (var y = -1; y < 2; y++) {
  74969. downSampleOffsets[id] = x / lastLuminance.width;
  74970. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74971. id += 2;
  74972. }
  74973. }
  74974. effect.setArray2("dsOffsets", downSampleOffsets);
  74975. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74976. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74977. lastLuminance = _this.luminancePostProcess;
  74978. }
  74979. else {
  74980. lastLuminance = pp;
  74981. }
  74982. };
  74983. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74984. pp.onAfterRender = function (effect) {
  74985. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74986. 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);
  74987. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74988. };
  74989. }
  74990. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74991. });
  74992. };
  74993. // Create HDR post-process
  74994. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74995. var _this = this;
  74996. 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);
  74997. var outputLiminance = 1;
  74998. var time = 0;
  74999. var lastTime = 0;
  75000. this.hdrPostProcess.onApply = function (effect) {
  75001. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75002. time += scene.getEngine().getDeltaTime();
  75003. if (outputLiminance < 0) {
  75004. outputLiminance = _this._hdrCurrentLuminance;
  75005. }
  75006. else {
  75007. var dt = (lastTime - time) / 1000.0;
  75008. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75009. outputLiminance += _this.hdrDecreaseRate * dt;
  75010. }
  75011. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75012. outputLiminance -= _this.hdrIncreaseRate * dt;
  75013. }
  75014. else {
  75015. outputLiminance = _this._hdrCurrentLuminance;
  75016. }
  75017. }
  75018. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75019. effect.setFloat("averageLuminance", outputLiminance);
  75020. lastTime = time;
  75021. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75022. };
  75023. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75024. };
  75025. // Create lens flare post-process
  75026. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75027. var _this = this;
  75028. 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);
  75029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75030. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75031. 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);
  75032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75033. var resolution = new BABYLON.Vector2(0, 0);
  75034. // Lens flare
  75035. this.lensFlarePostProcess.onApply = function (effect) {
  75036. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75037. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75038. effect.setFloat("strength", _this.lensFlareStrength);
  75039. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75040. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75041. // Shift
  75042. resolution.x = _this.lensFlarePostProcess.width;
  75043. resolution.y = _this.lensFlarePostProcess.height;
  75044. effect.setVector2("resolution", resolution);
  75045. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75046. };
  75047. // Compose
  75048. 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);
  75049. 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);
  75050. this.lensFlareComposePostProcess.onApply = function (effect) {
  75051. if (!_this._scene.activeCamera) {
  75052. return;
  75053. }
  75054. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75055. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75056. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75057. // Lens start rotation matrix
  75058. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75059. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75060. 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));
  75061. camRot *= 4.0;
  75062. 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);
  75063. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75064. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75065. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75066. };
  75067. };
  75068. // Create depth-of-field post-process
  75069. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75070. var _this = this;
  75071. 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);
  75072. this.depthOfFieldPostProcess.onApply = function (effect) {
  75073. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75074. effect.setTexture("depthSampler", _this._getDepthTexture());
  75075. effect.setFloat("distance", _this.depthOfFieldDistance);
  75076. };
  75077. // Add to pipeline
  75078. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75079. };
  75080. // Create motion blur post-process
  75081. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75082. var _this = this;
  75083. 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);
  75084. var motionScale = 0;
  75085. var prevViewProjection = BABYLON.Matrix.Identity();
  75086. var invViewProjection = BABYLON.Matrix.Identity();
  75087. var viewProjection = BABYLON.Matrix.Identity();
  75088. var screenSize = BABYLON.Vector2.Zero();
  75089. this.motionBlurPostProcess.onApply = function (effect) {
  75090. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75091. viewProjection.invertToRef(invViewProjection);
  75092. effect.setMatrix("inverseViewProjection", invViewProjection);
  75093. effect.setMatrix("prevViewProjection", prevViewProjection);
  75094. prevViewProjection = viewProjection;
  75095. screenSize.x = _this.motionBlurPostProcess.width;
  75096. screenSize.y = _this.motionBlurPostProcess.height;
  75097. effect.setVector2("screenSize", screenSize);
  75098. motionScale = scene.getEngine().getFps() / 60.0;
  75099. effect.setFloat("motionScale", motionScale);
  75100. effect.setFloat("motionStrength", _this.motionStrength);
  75101. effect.setTexture("depthSampler", _this._getDepthTexture());
  75102. };
  75103. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75104. };
  75105. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75106. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75107. var renderer = this._scene.enableGeometryBufferRenderer();
  75108. return renderer.getGBuffer().textures[0];
  75109. }
  75110. return this._scene.enableDepthRenderer().getDepthMap();
  75111. };
  75112. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75113. for (var i = 0; i < this._cameras.length; i++) {
  75114. var camera = this._cameras[i];
  75115. if (this.originalPostProcess) {
  75116. this.originalPostProcess.dispose(camera);
  75117. }
  75118. if (this.downSampleX4PostProcess) {
  75119. this.downSampleX4PostProcess.dispose(camera);
  75120. }
  75121. if (this.brightPassPostProcess) {
  75122. this.brightPassPostProcess.dispose(camera);
  75123. }
  75124. if (this.textureAdderPostProcess) {
  75125. this.textureAdderPostProcess.dispose(camera);
  75126. }
  75127. if (this.textureAdderFinalPostProcess) {
  75128. this.textureAdderFinalPostProcess.dispose(camera);
  75129. }
  75130. if (this.volumetricLightPostProcess) {
  75131. this.volumetricLightPostProcess.dispose(camera);
  75132. }
  75133. if (this.volumetricLightSmoothXPostProcess) {
  75134. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75135. }
  75136. if (this.volumetricLightSmoothYPostProcess) {
  75137. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75138. }
  75139. if (this.volumetricLightMergePostProces) {
  75140. this.volumetricLightMergePostProces.dispose(camera);
  75141. }
  75142. if (this.volumetricLightFinalPostProcess) {
  75143. this.volumetricLightFinalPostProcess.dispose(camera);
  75144. }
  75145. if (this.lensFlarePostProcess) {
  75146. this.lensFlarePostProcess.dispose(camera);
  75147. }
  75148. if (this.lensFlareComposePostProcess) {
  75149. this.lensFlareComposePostProcess.dispose(camera);
  75150. }
  75151. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75152. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75153. }
  75154. if (this.luminancePostProcess) {
  75155. this.luminancePostProcess.dispose(camera);
  75156. }
  75157. if (this.hdrPostProcess) {
  75158. this.hdrPostProcess.dispose(camera);
  75159. }
  75160. if (this.hdrFinalPostProcess) {
  75161. this.hdrFinalPostProcess.dispose(camera);
  75162. }
  75163. if (this.depthOfFieldPostProcess) {
  75164. this.depthOfFieldPostProcess.dispose(camera);
  75165. }
  75166. if (this.motionBlurPostProcess) {
  75167. this.motionBlurPostProcess.dispose(camera);
  75168. }
  75169. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75170. this.blurHPostProcesses[j].dispose(camera);
  75171. }
  75172. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75173. this.blurVPostProcesses[j].dispose(camera);
  75174. }
  75175. }
  75176. this.originalPostProcess = null;
  75177. this.downSampleX4PostProcess = null;
  75178. this.brightPassPostProcess = null;
  75179. this.textureAdderPostProcess = null;
  75180. this.textureAdderFinalPostProcess = null;
  75181. this.volumetricLightPostProcess = null;
  75182. this.volumetricLightSmoothXPostProcess = null;
  75183. this.volumetricLightSmoothYPostProcess = null;
  75184. this.volumetricLightMergePostProces = null;
  75185. this.volumetricLightFinalPostProcess = null;
  75186. this.lensFlarePostProcess = null;
  75187. this.lensFlareComposePostProcess = null;
  75188. this.luminancePostProcess = null;
  75189. this.hdrPostProcess = null;
  75190. this.hdrFinalPostProcess = null;
  75191. this.depthOfFieldPostProcess = null;
  75192. this.motionBlurPostProcess = null;
  75193. this.luminanceDownSamplePostProcesses = [];
  75194. this.blurHPostProcesses = [];
  75195. this.blurVPostProcesses = [];
  75196. };
  75197. /**
  75198. * Dispose of the pipeline and stop all post processes
  75199. */
  75200. StandardRenderingPipeline.prototype.dispose = function () {
  75201. this._disposePostProcesses();
  75202. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75203. _super.prototype.dispose.call(this);
  75204. };
  75205. /**
  75206. * Serialize the rendering pipeline (Used when exporting)
  75207. * @returns the serialized object
  75208. */
  75209. StandardRenderingPipeline.prototype.serialize = function () {
  75210. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75211. if (this.sourceLight) {
  75212. serializationObject.sourceLightId = this.sourceLight.id;
  75213. }
  75214. serializationObject.customType = "StandardRenderingPipeline";
  75215. return serializationObject;
  75216. };
  75217. /**
  75218. * Parse the serialized pipeline
  75219. * @param source Source pipeline.
  75220. * @param scene The scene to load the pipeline to.
  75221. * @param rootUrl The URL of the serialized pipeline.
  75222. * @returns An instantiated pipeline from the serialized object.
  75223. */
  75224. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75225. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75226. if (source.sourceLightId) {
  75227. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75228. }
  75229. return p;
  75230. };
  75231. // Luminance steps
  75232. StandardRenderingPipeline.LuminanceSteps = 6;
  75233. __decorate([
  75234. BABYLON.serialize()
  75235. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75236. __decorate([
  75237. BABYLON.serialize()
  75238. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75239. __decorate([
  75240. BABYLON.serialize()
  75241. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75242. __decorate([
  75243. BABYLON.serialize()
  75244. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75245. __decorate([
  75246. BABYLON.serializeAsTexture("lensTexture")
  75247. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75248. __decorate([
  75249. BABYLON.serialize()
  75250. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75251. __decorate([
  75252. BABYLON.serialize()
  75253. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75254. __decorate([
  75255. BABYLON.serialize()
  75256. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75257. __decorate([
  75258. BABYLON.serialize()
  75259. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75260. __decorate([
  75261. BABYLON.serialize()
  75262. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75263. __decorate([
  75264. BABYLON.serialize()
  75265. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75266. __decorate([
  75267. BABYLON.serializeAsTexture("lensColorTexture")
  75268. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75269. __decorate([
  75270. BABYLON.serialize()
  75271. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75272. __decorate([
  75273. BABYLON.serialize()
  75274. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75275. __decorate([
  75276. BABYLON.serialize()
  75277. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75278. __decorate([
  75279. BABYLON.serialize()
  75280. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75281. __decorate([
  75282. BABYLON.serializeAsTexture("lensStarTexture")
  75283. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75284. __decorate([
  75285. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75286. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75287. __decorate([
  75288. BABYLON.serialize()
  75289. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75290. __decorate([
  75291. BABYLON.serialize()
  75292. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75293. __decorate([
  75294. BABYLON.serialize()
  75295. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75296. __decorate([
  75297. BABYLON.serialize()
  75298. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75299. __decorate([
  75300. BABYLON.serialize()
  75301. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75302. __decorate([
  75303. BABYLON.serialize()
  75304. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75305. __decorate([
  75306. BABYLON.serialize()
  75307. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75308. __decorate([
  75309. BABYLON.serialize()
  75310. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75311. __decorate([
  75312. BABYLON.serialize()
  75313. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75314. __decorate([
  75315. BABYLON.serialize()
  75316. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75317. __decorate([
  75318. BABYLON.serialize()
  75319. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75320. __decorate([
  75321. BABYLON.serialize()
  75322. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75323. return StandardRenderingPipeline;
  75324. }(BABYLON.PostProcessRenderPipeline));
  75325. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75326. })(BABYLON || (BABYLON = {}));
  75327. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75328. var BABYLON;
  75329. (function (BABYLON) {
  75330. var FxaaPostProcess = /** @class */ (function (_super) {
  75331. __extends(FxaaPostProcess, _super);
  75332. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75333. if (camera === void 0) { camera = null; }
  75334. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75335. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75336. var defines = _this._getDefines();
  75337. _this.updateEffect(defines);
  75338. _this.onApplyObservable.add(function (effect) {
  75339. var texelSize = _this.texelSize;
  75340. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75341. });
  75342. return _this;
  75343. }
  75344. FxaaPostProcess.prototype._getDefines = function () {
  75345. var engine = this.getEngine();
  75346. if (!engine) {
  75347. return null;
  75348. }
  75349. var glInfo = engine.getGlInfo();
  75350. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75351. return "#define MALI 1\n";
  75352. }
  75353. return null;
  75354. };
  75355. return FxaaPostProcess;
  75356. }(BABYLON.PostProcess));
  75357. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75358. })(BABYLON || (BABYLON = {}));
  75359. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75360. var BABYLON;
  75361. (function (BABYLON) {
  75362. /**
  75363. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75364. */
  75365. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75366. __extends(ChromaticAberrationPostProcess, _super);
  75367. /**
  75368. * Creates a new instance ChromaticAberrationPostProcess
  75369. * @param name The name of the effect.
  75370. * @param screenWidth The width of the screen to apply the effect on.
  75371. * @param screenHeight The height of the screen to apply the effect on.
  75372. * @param options The required width/height ratio to downsize to before computing the render pass.
  75373. * @param camera The camera to apply the render pass to.
  75374. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75375. * @param engine The engine which the post process will be applied. (default: current engine)
  75376. * @param reusable If the post process can be reused on the same frame. (default: false)
  75377. * @param textureType Type of textures used when performing the post process. (default: 0)
  75378. * @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)
  75379. */
  75380. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75381. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75382. if (blockCompilation === void 0) { blockCompilation = false; }
  75383. 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;
  75384. /**
  75385. * The amount of seperation of rgb channels (default: 30)
  75386. */
  75387. _this.aberrationAmount = 30;
  75388. /**
  75389. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75390. */
  75391. _this.radialIntensity = 0;
  75392. /**
  75393. * 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))
  75394. */
  75395. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75396. /**
  75397. * 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))
  75398. */
  75399. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75400. _this.onApplyObservable.add(function (effect) {
  75401. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75402. effect.setFloat('screen_width', screenWidth);
  75403. effect.setFloat('screen_height', screenHeight);
  75404. effect.setFloat('radialIntensity', _this.radialIntensity);
  75405. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75406. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75407. });
  75408. return _this;
  75409. }
  75410. return ChromaticAberrationPostProcess;
  75411. }(BABYLON.PostProcess));
  75412. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75413. })(BABYLON || (BABYLON = {}));
  75414. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75415. var BABYLON;
  75416. (function (BABYLON) {
  75417. /**
  75418. * The GrainPostProcess adds noise to the image at mid luminance levels
  75419. */
  75420. var GrainPostProcess = /** @class */ (function (_super) {
  75421. __extends(GrainPostProcess, _super);
  75422. /**
  75423. * Creates a new instance of @see GrainPostProcess
  75424. * @param name The name of the effect.
  75425. * @param options The required width/height ratio to downsize to before computing the render pass.
  75426. * @param camera The camera to apply the render pass to.
  75427. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75428. * @param engine The engine which the post process will be applied. (default: current engine)
  75429. * @param reusable If the post process can be reused on the same frame. (default: false)
  75430. * @param textureType Type of textures used when performing the post process. (default: 0)
  75431. * @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)
  75432. */
  75433. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75434. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75435. if (blockCompilation === void 0) { blockCompilation = false; }
  75436. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75437. /**
  75438. * The intensity of the grain added (default: 30)
  75439. */
  75440. _this.intensity = 30;
  75441. /**
  75442. * If the grain should be randomized on every frame
  75443. */
  75444. _this.animated = false;
  75445. _this.onApplyObservable.add(function (effect) {
  75446. effect.setFloat('intensity', _this.intensity);
  75447. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75448. });
  75449. return _this;
  75450. }
  75451. return GrainPostProcess;
  75452. }(BABYLON.PostProcess));
  75453. BABYLON.GrainPostProcess = GrainPostProcess;
  75454. })(BABYLON || (BABYLON = {}));
  75455. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75456. var BABYLON;
  75457. (function (BABYLON) {
  75458. /**
  75459. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75460. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75461. */
  75462. var SharpenPostProcess = /** @class */ (function (_super) {
  75463. __extends(SharpenPostProcess, _super);
  75464. /**
  75465. * Creates a new instance ConvolutionPostProcess
  75466. * @param name The name of the effect.
  75467. * @param options The required width/height ratio to downsize to before computing the render pass.
  75468. * @param camera The camera to apply the render pass to.
  75469. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75470. * @param engine The engine which the post process will be applied. (default: current engine)
  75471. * @param reusable If the post process can be reused on the same frame. (default: false)
  75472. * @param textureType Type of textures used when performing the post process. (default: 0)
  75473. * @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)
  75474. */
  75475. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75476. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75477. if (blockCompilation === void 0) { blockCompilation = false; }
  75478. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75479. /**
  75480. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75481. */
  75482. _this.colorAmount = 1.0;
  75483. /**
  75484. * How much sharpness should be applied (default: 0.3)
  75485. */
  75486. _this.edgeAmount = 0.3;
  75487. _this.onApply = function (effect) {
  75488. effect.setFloat2("screenSize", _this.width, _this.height);
  75489. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75490. };
  75491. return _this;
  75492. }
  75493. return SharpenPostProcess;
  75494. }(BABYLON.PostProcess));
  75495. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75496. })(BABYLON || (BABYLON = {}));
  75497. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75498. var BABYLON;
  75499. (function (BABYLON) {
  75500. /**
  75501. * The Blur Post Process which blurs an image based on a kernel and direction.
  75502. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75503. */
  75504. var BlurPostProcess = /** @class */ (function (_super) {
  75505. __extends(BlurPostProcess, _super);
  75506. /**
  75507. * Creates a new instance BlurPostProcess
  75508. * @param name The name of the effect.
  75509. * @param direction The direction in which to blur the image.
  75510. * @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.
  75511. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75512. * @param camera The camera to apply the render pass to.
  75513. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75514. * @param engine The engine which the post process will be applied. (default: current engine)
  75515. * @param reusable If the post process can be reused on the same frame. (default: false)
  75516. * @param textureType Type of textures used when performing the post process. (default: 0)
  75517. * @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)
  75518. */
  75519. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75521. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75522. if (defines === void 0) { defines = ""; }
  75523. if (blockCompilation === void 0) { blockCompilation = false; }
  75524. 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;
  75525. _this.direction = direction;
  75526. _this.blockCompilation = blockCompilation;
  75527. _this._packedFloat = false;
  75528. _this._staticDefines = "";
  75529. _this._staticDefines = defines;
  75530. _this.onApplyObservable.add(function (effect) {
  75531. if (_this._outputTexture) {
  75532. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75533. }
  75534. else {
  75535. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75536. }
  75537. });
  75538. _this.kernel = kernel;
  75539. return _this;
  75540. }
  75541. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75542. /**
  75543. * Gets the length in pixels of the blur sample region
  75544. */
  75545. get: function () {
  75546. return this._idealKernel;
  75547. },
  75548. /**
  75549. * Sets the length in pixels of the blur sample region
  75550. */
  75551. set: function (v) {
  75552. if (this._idealKernel === v) {
  75553. return;
  75554. }
  75555. v = Math.max(v, 1);
  75556. this._idealKernel = v;
  75557. this._kernel = this._nearestBestKernel(v);
  75558. if (!this.blockCompilation) {
  75559. this._updateParameters();
  75560. }
  75561. },
  75562. enumerable: true,
  75563. configurable: true
  75564. });
  75565. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75566. /**
  75567. * Gets wether or not the blur is unpacking/repacking floats
  75568. */
  75569. get: function () {
  75570. return this._packedFloat;
  75571. },
  75572. /**
  75573. * Sets wether or not the blur needs to unpack/repack floats
  75574. */
  75575. set: function (v) {
  75576. if (this._packedFloat === v) {
  75577. return;
  75578. }
  75579. this._packedFloat = v;
  75580. if (!this.blockCompilation) {
  75581. this._updateParameters();
  75582. }
  75583. },
  75584. enumerable: true,
  75585. configurable: true
  75586. });
  75587. /**
  75588. * Updates the effect with the current post process compile time values and recompiles the shader.
  75589. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75590. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75591. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75592. * @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
  75593. * @param onCompiled Called when the shader has been compiled.
  75594. * @param onError Called if there is an error when compiling a shader.
  75595. */
  75596. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75597. if (defines === void 0) { defines = null; }
  75598. if (uniforms === void 0) { uniforms = null; }
  75599. if (samplers === void 0) { samplers = null; }
  75600. this._updateParameters(onCompiled, onError);
  75601. };
  75602. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75603. // Generate sampling offsets and weights
  75604. var N = this._kernel;
  75605. var centerIndex = (N - 1) / 2;
  75606. // Generate Gaussian sampling weights over kernel
  75607. var offsets = [];
  75608. var weights = [];
  75609. var totalWeight = 0;
  75610. for (var i = 0; i < N; i++) {
  75611. var u = i / (N - 1);
  75612. var w = this._gaussianWeight(u * 2.0 - 1);
  75613. offsets[i] = (i - centerIndex);
  75614. weights[i] = w;
  75615. totalWeight += w;
  75616. }
  75617. // Normalize weights
  75618. for (var i = 0; i < weights.length; i++) {
  75619. weights[i] /= totalWeight;
  75620. }
  75621. // Optimize: combine samples to take advantage of hardware linear sampling
  75622. // Walk from left to center, combining pairs (symmetrically)
  75623. var linearSamplingWeights = [];
  75624. var linearSamplingOffsets = [];
  75625. var linearSamplingMap = [];
  75626. for (var i = 0; i <= centerIndex; i += 2) {
  75627. var j = Math.min(i + 1, Math.floor(centerIndex));
  75628. var singleCenterSample = i === j;
  75629. if (singleCenterSample) {
  75630. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75631. }
  75632. else {
  75633. var sharedCell = j === centerIndex;
  75634. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75635. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75636. if (offsetLinear === 0) {
  75637. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75638. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75639. }
  75640. else {
  75641. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75642. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75643. }
  75644. }
  75645. }
  75646. for (var i = 0; i < linearSamplingMap.length; i++) {
  75647. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75648. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75649. }
  75650. // Replace with optimized
  75651. offsets = linearSamplingOffsets;
  75652. weights = linearSamplingWeights;
  75653. // Generate shaders
  75654. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75655. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75656. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75657. var defines = "";
  75658. defines += this._staticDefines;
  75659. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75660. if (this._staticDefines.indexOf("DOF") != -1) {
  75661. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75662. varyingCount--;
  75663. }
  75664. for (var i = 0; i < varyingCount; i++) {
  75665. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75666. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75667. }
  75668. var depCount = 0;
  75669. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75670. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75671. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75672. depCount++;
  75673. }
  75674. if (this.packedFloat) {
  75675. defines += "#define PACKEDFLOAT 1";
  75676. }
  75677. this.blockCompilation = false;
  75678. _super.prototype.updateEffect.call(this, defines, null, null, {
  75679. varyingCount: varyingCount,
  75680. depCount: depCount
  75681. }, onCompiled, onError);
  75682. };
  75683. /**
  75684. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75685. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75686. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75687. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75688. * The gaps between physical kernels are compensated for in the weighting of the samples
  75689. * @param idealKernel Ideal blur kernel.
  75690. * @return Nearest best kernel.
  75691. */
  75692. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75693. var v = Math.round(idealKernel);
  75694. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75695. var k = _a[_i];
  75696. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75697. return Math.max(k, 3);
  75698. }
  75699. }
  75700. return Math.max(v, 3);
  75701. };
  75702. /**
  75703. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75704. * @param x The point on the Gaussian distribution to sample.
  75705. * @return the value of the Gaussian function at x.
  75706. */
  75707. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75708. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75709. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75710. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75711. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75712. // truncated at around 1.3% of peak strength.
  75713. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75714. var sigma = (1 / 3);
  75715. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75716. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75717. var weight = (1.0 / denominator) * Math.exp(exponent);
  75718. return weight;
  75719. };
  75720. /**
  75721. * Generates a string that can be used as a floating point number in GLSL.
  75722. * @param x Value to print.
  75723. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75724. * @return GLSL float string.
  75725. */
  75726. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75727. if (decimalFigures === void 0) { decimalFigures = 8; }
  75728. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75729. };
  75730. return BlurPostProcess;
  75731. }(BABYLON.PostProcess));
  75732. BABYLON.BlurPostProcess = BlurPostProcess;
  75733. })(BABYLON || (BABYLON = {}));
  75734. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75735. var BABYLON;
  75736. (function (BABYLON) {
  75737. /**
  75738. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75739. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75740. * based on samples that have a large difference in distance than the center pixel.
  75741. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75742. */
  75743. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75744. __extends(DepthOfFieldBlurPostProcess, _super);
  75745. /**
  75746. * Creates a new instance CircleOfConfusionPostProcess
  75747. * @param name The name of the effect.
  75748. * @param scene The scene the effect belongs to.
  75749. * @param direction The direction the blur should be applied.
  75750. * @param kernel The size of the kernel used to blur.
  75751. * @param options The required width/height ratio to downsize to before computing the render pass.
  75752. * @param camera The camera to apply the render pass to.
  75753. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75754. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75755. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75756. * @param engine The engine which the post process will be applied. (default: current engine)
  75757. * @param reusable If the post process can be reused on the same frame. (default: false)
  75758. * @param textureType Type of textures used when performing the post process. (default: 0)
  75759. * @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)
  75760. */
  75761. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75762. if (imageToBlur === void 0) { imageToBlur = null; }
  75763. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75764. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75765. if (blockCompilation === void 0) { blockCompilation = false; }
  75766. 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;
  75767. _this.direction = direction;
  75768. _this.onApplyObservable.add(function (effect) {
  75769. if (imageToBlur != null) {
  75770. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75771. }
  75772. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75773. if (scene.activeCamera) {
  75774. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75775. }
  75776. });
  75777. return _this;
  75778. }
  75779. return DepthOfFieldBlurPostProcess;
  75780. }(BABYLON.BlurPostProcess));
  75781. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75782. })(BABYLON || (BABYLON = {}));
  75783. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75784. var BABYLON;
  75785. (function (BABYLON) {
  75786. /**
  75787. * Options to be set when merging outputs from the default pipeline.
  75788. */
  75789. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75790. function DepthOfFieldMergePostProcessOptions() {
  75791. }
  75792. return DepthOfFieldMergePostProcessOptions;
  75793. }());
  75794. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75795. /**
  75796. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75797. */
  75798. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75799. __extends(DepthOfFieldMergePostProcess, _super);
  75800. /**
  75801. * Creates a new instance of DepthOfFieldMergePostProcess
  75802. * @param name The name of the effect.
  75803. * @param originalFromInput Post process which's input will be used for the merge.
  75804. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75805. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75806. * @param options The required width/height ratio to downsize to before computing the render pass.
  75807. * @param camera The camera to apply the render pass to.
  75808. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75809. * @param engine The engine which the post process will be applied. (default: current engine)
  75810. * @param reusable If the post process can be reused on the same frame. (default: false)
  75811. * @param textureType Type of textures used when performing the post process. (default: 0)
  75812. * @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)
  75813. */
  75814. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75815. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75816. if (blockCompilation === void 0) { blockCompilation = false; }
  75817. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75818. _this.blurSteps = blurSteps;
  75819. _this.onApplyObservable.add(function (effect) {
  75820. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75821. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75822. blurSteps.forEach(function (step, index) {
  75823. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75824. });
  75825. });
  75826. if (!blockCompilation) {
  75827. _this.updateEffect();
  75828. }
  75829. return _this;
  75830. }
  75831. /**
  75832. * Updates the effect with the current post process compile time values and recompiles the shader.
  75833. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75834. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75835. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75836. * @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
  75837. * @param onCompiled Called when the shader has been compiled.
  75838. * @param onError Called if there is an error when compiling a shader.
  75839. */
  75840. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75841. if (defines === void 0) { defines = null; }
  75842. if (uniforms === void 0) { uniforms = null; }
  75843. if (samplers === void 0) { samplers = null; }
  75844. if (!defines) {
  75845. defines = "";
  75846. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75847. }
  75848. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75849. };
  75850. return DepthOfFieldMergePostProcess;
  75851. }(BABYLON.PostProcess));
  75852. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75853. })(BABYLON || (BABYLON = {}));
  75854. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75855. var BABYLON;
  75856. (function (BABYLON) {
  75857. /**
  75858. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75859. */
  75860. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75861. __extends(CircleOfConfusionPostProcess, _super);
  75862. /**
  75863. * Creates a new instance CircleOfConfusionPostProcess
  75864. * @param name The name of the effect.
  75865. * @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.
  75866. * @param options The required width/height ratio to downsize to before computing the render pass.
  75867. * @param camera The camera to apply the render pass to.
  75868. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75869. * @param engine The engine which the post process will be applied. (default: current engine)
  75870. * @param reusable If the post process can be reused on the same frame. (default: false)
  75871. * @param textureType Type of textures used when performing the post process. (default: 0)
  75872. * @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)
  75873. */
  75874. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75875. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75876. if (blockCompilation === void 0) { blockCompilation = false; }
  75877. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75878. /**
  75879. * 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.
  75880. */
  75881. _this.lensSize = 50;
  75882. /**
  75883. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75884. */
  75885. _this.fStop = 1.4;
  75886. /**
  75887. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75888. */
  75889. _this.focusDistance = 2000;
  75890. /**
  75891. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75892. */
  75893. _this.focalLength = 50;
  75894. _this._depthTexture = null;
  75895. _this._depthTexture = depthTexture;
  75896. _this.onApplyObservable.add(function (effect) {
  75897. if (!_this._depthTexture) {
  75898. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75899. return;
  75900. }
  75901. effect.setTexture("depthSampler", _this._depthTexture);
  75902. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75903. var aperture = _this.lensSize / _this.fStop;
  75904. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75905. effect.setFloat('focusDistance', _this.focusDistance);
  75906. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75907. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75908. });
  75909. return _this;
  75910. }
  75911. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75912. /**
  75913. * 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.
  75914. */
  75915. set: function (value) {
  75916. this._depthTexture = value;
  75917. },
  75918. enumerable: true,
  75919. configurable: true
  75920. });
  75921. return CircleOfConfusionPostProcess;
  75922. }(BABYLON.PostProcess));
  75923. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75924. })(BABYLON || (BABYLON = {}));
  75925. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75926. var BABYLON;
  75927. (function (BABYLON) {
  75928. /**
  75929. * Specifies the level of max blur that should be applied when using the depth of field effect
  75930. */
  75931. var DepthOfFieldEffectBlurLevel;
  75932. (function (DepthOfFieldEffectBlurLevel) {
  75933. /**
  75934. * Subtle blur
  75935. */
  75936. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75937. /**
  75938. * Medium blur
  75939. */
  75940. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75941. /**
  75942. * Large blur
  75943. */
  75944. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75945. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75946. ;
  75947. /**
  75948. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75949. */
  75950. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75951. __extends(DepthOfFieldEffect, _super);
  75952. /**
  75953. * Creates a new instance DepthOfFieldEffect
  75954. * @param scene The scene the effect belongs to.
  75955. * @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.
  75956. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75957. * @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)
  75958. */
  75959. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75960. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75961. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75962. if (blockCompilation === void 0) { blockCompilation = false; }
  75963. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75964. return _this._effects;
  75965. }, true) || this;
  75966. /**
  75967. * Internal post processes in depth of field effect
  75968. */
  75969. _this._effects = [];
  75970. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75971. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75972. // 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)
  75973. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75974. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75975. _this._depthOfFieldBlurY = [];
  75976. _this._depthOfFieldBlurX = [];
  75977. var blurCount = 1;
  75978. var kernelSize = 15;
  75979. switch (blurLevel) {
  75980. case DepthOfFieldEffectBlurLevel.High: {
  75981. blurCount = 3;
  75982. kernelSize = 51;
  75983. break;
  75984. }
  75985. case DepthOfFieldEffectBlurLevel.Medium: {
  75986. blurCount = 2;
  75987. kernelSize = 31;
  75988. break;
  75989. }
  75990. default: {
  75991. kernelSize = 15;
  75992. blurCount = 1;
  75993. break;
  75994. }
  75995. }
  75996. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75997. var ratio = 1.0;
  75998. for (var i = 0; i < blurCount; i++) {
  75999. 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);
  76000. blurY.autoClear = false;
  76001. ratio = 0.75 / Math.pow(2, i);
  76002. 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);
  76003. blurX.autoClear = false;
  76004. _this._depthOfFieldBlurY.push(blurY);
  76005. _this._depthOfFieldBlurX.push(blurX);
  76006. }
  76007. // Set all post processes on the effect.
  76008. _this._effects = [_this._circleOfConfusion];
  76009. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76010. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76011. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76012. }
  76013. // Merge blurred images with original image based on circleOfConfusion
  76014. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76015. _this._dofMerge.autoClear = false;
  76016. _this._effects.push(_this._dofMerge);
  76017. return _this;
  76018. }
  76019. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76020. get: function () {
  76021. return this._circleOfConfusion.focalLength;
  76022. },
  76023. /**
  76024. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76025. */
  76026. set: function (value) {
  76027. this._circleOfConfusion.focalLength = value;
  76028. },
  76029. enumerable: true,
  76030. configurable: true
  76031. });
  76032. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76033. get: function () {
  76034. return this._circleOfConfusion.fStop;
  76035. },
  76036. /**
  76037. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76038. */
  76039. set: function (value) {
  76040. this._circleOfConfusion.fStop = value;
  76041. },
  76042. enumerable: true,
  76043. configurable: true
  76044. });
  76045. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76046. get: function () {
  76047. return this._circleOfConfusion.focusDistance;
  76048. },
  76049. /**
  76050. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76051. */
  76052. set: function (value) {
  76053. this._circleOfConfusion.focusDistance = value;
  76054. },
  76055. enumerable: true,
  76056. configurable: true
  76057. });
  76058. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76059. get: function () {
  76060. return this._circleOfConfusion.lensSize;
  76061. },
  76062. /**
  76063. * 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.
  76064. */
  76065. set: function (value) {
  76066. this._circleOfConfusion.lensSize = value;
  76067. },
  76068. enumerable: true,
  76069. configurable: true
  76070. });
  76071. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76072. /**
  76073. * 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.
  76074. */
  76075. set: function (value) {
  76076. this._circleOfConfusion.depthTexture = value;
  76077. },
  76078. enumerable: true,
  76079. configurable: true
  76080. });
  76081. /**
  76082. * Disposes each of the internal effects for a given camera.
  76083. * @param camera The camera to dispose the effect on.
  76084. */
  76085. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76086. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76087. this._effects[effectIndex].dispose(camera);
  76088. }
  76089. };
  76090. /**
  76091. * Internal
  76092. */
  76093. DepthOfFieldEffect.prototype._updateEffects = function () {
  76094. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76095. this._effects[effectIndex].updateEffect();
  76096. }
  76097. };
  76098. /**
  76099. * Internal
  76100. * @returns if all the contained post processes are ready.
  76101. */
  76102. DepthOfFieldEffect.prototype._isReady = function () {
  76103. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76104. if (!this._effects[effectIndex].isReady()) {
  76105. return false;
  76106. }
  76107. }
  76108. return true;
  76109. };
  76110. return DepthOfFieldEffect;
  76111. }(BABYLON.PostProcessRenderEffect));
  76112. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76113. })(BABYLON || (BABYLON = {}));
  76114. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76115. var BABYLON;
  76116. (function (BABYLON) {
  76117. /**
  76118. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76119. */
  76120. var BloomMergePostProcess = /** @class */ (function (_super) {
  76121. __extends(BloomMergePostProcess, _super);
  76122. /**
  76123. * Creates a new instance of @see BloomMergePostProcess
  76124. * @param name The name of the effect.
  76125. * @param originalFromInput Post process which's input will be used for the merge.
  76126. * @param blurred Blurred highlights post process which's output will be used.
  76127. * @param weight Weight of the bloom to be added to the original input.
  76128. * @param options The required width/height ratio to downsize to before computing the render pass.
  76129. * @param camera The camera to apply the render pass to.
  76130. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76131. * @param engine The engine which the post process will be applied. (default: current engine)
  76132. * @param reusable If the post process can be reused on the same frame. (default: false)
  76133. * @param textureType Type of textures used when performing the post process. (default: 0)
  76134. * @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)
  76135. */
  76136. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76137. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76138. if (blockCompilation === void 0) { blockCompilation = false; }
  76139. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76140. _this.weight = weight;
  76141. _this.onApplyObservable.add(function (effect) {
  76142. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76143. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76144. effect.setFloat("bloomWeight", _this.weight);
  76145. });
  76146. if (!blockCompilation) {
  76147. _this.updateEffect();
  76148. }
  76149. return _this;
  76150. }
  76151. return BloomMergePostProcess;
  76152. }(BABYLON.PostProcess));
  76153. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76154. })(BABYLON || (BABYLON = {}));
  76155. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76156. var BABYLON;
  76157. (function (BABYLON) {
  76158. /**
  76159. * 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.
  76160. */
  76161. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76162. __extends(ExtractHighlightsPostProcess, _super);
  76163. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76164. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76165. if (blockCompilation === void 0) { blockCompilation = false; }
  76166. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76167. /**
  76168. * The luminance threshold, pixels below this value will be set to black.
  76169. */
  76170. _this.threshold = 0.9;
  76171. /**
  76172. * Internal
  76173. */
  76174. _this._exposure = 1;
  76175. /**
  76176. * Post process which has the input texture to be used when performing highlight extraction
  76177. */
  76178. _this._inputPostProcess = null;
  76179. _this.onApplyObservable.add(function (effect) {
  76180. if (_this._inputPostProcess) {
  76181. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76182. }
  76183. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76184. effect.setFloat('exposure', _this._exposure);
  76185. });
  76186. return _this;
  76187. }
  76188. return ExtractHighlightsPostProcess;
  76189. }(BABYLON.PostProcess));
  76190. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76191. })(BABYLON || (BABYLON = {}));
  76192. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76193. var BABYLON;
  76194. (function (BABYLON) {
  76195. /**
  76196. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76197. */
  76198. var BloomEffect = /** @class */ (function (_super) {
  76199. __extends(BloomEffect, _super);
  76200. /**
  76201. * Creates a new instance of @see BloomEffect
  76202. * @param scene The scene the effect belongs to.
  76203. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76204. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76205. * @param bloomWeight The the strength of bloom.
  76206. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76207. * @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)
  76208. */
  76209. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76210. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76211. if (blockCompilation === void 0) { blockCompilation = false; }
  76212. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76213. return _this._effects;
  76214. }, true) || this;
  76215. _this.bloomScale = bloomScale;
  76216. /**
  76217. * Internal
  76218. */
  76219. _this._effects = [];
  76220. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76221. _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);
  76222. _this._blurX.alwaysForcePOT = true;
  76223. _this._blurX.autoClear = false;
  76224. _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);
  76225. _this._blurY.alwaysForcePOT = true;
  76226. _this._blurY.autoClear = false;
  76227. _this.kernel = bloomKernel;
  76228. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76229. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76230. _this._merge.autoClear = false;
  76231. _this._effects.push(_this._merge);
  76232. return _this;
  76233. }
  76234. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76235. /**
  76236. * The luminance threshold to find bright areas of the image to bloom.
  76237. */
  76238. get: function () {
  76239. return this._downscale.threshold;
  76240. },
  76241. set: function (value) {
  76242. this._downscale.threshold = value;
  76243. },
  76244. enumerable: true,
  76245. configurable: true
  76246. });
  76247. Object.defineProperty(BloomEffect.prototype, "weight", {
  76248. /**
  76249. * The strength of the bloom.
  76250. */
  76251. get: function () {
  76252. return this._merge.weight;
  76253. },
  76254. set: function (value) {
  76255. this._merge.weight = value;
  76256. },
  76257. enumerable: true,
  76258. configurable: true
  76259. });
  76260. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76261. /**
  76262. * Specifies the size of the bloom blur kernel, relative to the final output size
  76263. */
  76264. get: function () {
  76265. return this._blurX.kernel / this.bloomScale;
  76266. },
  76267. set: function (value) {
  76268. this._blurX.kernel = value * this.bloomScale;
  76269. this._blurY.kernel = value * this.bloomScale;
  76270. },
  76271. enumerable: true,
  76272. configurable: true
  76273. });
  76274. /**
  76275. * Disposes each of the internal effects for a given camera.
  76276. * @param camera The camera to dispose the effect on.
  76277. */
  76278. BloomEffect.prototype.disposeEffects = function (camera) {
  76279. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76280. this._effects[effectIndex].dispose(camera);
  76281. }
  76282. };
  76283. /**
  76284. * Internal
  76285. */
  76286. BloomEffect.prototype._updateEffects = function () {
  76287. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76288. this._effects[effectIndex].updateEffect();
  76289. }
  76290. };
  76291. /**
  76292. * Internal
  76293. * @returns if all the contained post processes are ready.
  76294. */
  76295. BloomEffect.prototype._isReady = function () {
  76296. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76297. if (!this._effects[effectIndex].isReady()) {
  76298. return false;
  76299. }
  76300. }
  76301. return true;
  76302. };
  76303. return BloomEffect;
  76304. }(BABYLON.PostProcessRenderEffect));
  76305. BABYLON.BloomEffect = BloomEffect;
  76306. })(BABYLON || (BABYLON = {}));
  76307. //# sourceMappingURL=babylon.bloomEffect.js.map
  76308. var BABYLON;
  76309. (function (BABYLON) {
  76310. /**
  76311. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76312. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76313. */
  76314. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76315. __extends(DefaultRenderingPipeline, _super);
  76316. /**
  76317. * @constructor
  76318. * @param {string} name - The rendering pipeline name (default: "")
  76319. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76320. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76321. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76322. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76323. */
  76324. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76325. if (name === void 0) { name = ""; }
  76326. if (hdr === void 0) { hdr = true; }
  76327. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76328. if (automaticBuild === void 0) { automaticBuild = true; }
  76329. var _this = _super.call(this, scene.getEngine(), name) || this;
  76330. _this._originalCameras = [];
  76331. /**
  76332. * ID of the sharpen post process,
  76333. */
  76334. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76335. /**
  76336. * ID of the image processing post process;
  76337. */
  76338. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76339. /**
  76340. * ID of the Fast Approximate Anti-Aliasing post process;
  76341. */
  76342. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76343. /**
  76344. * ID of the chromatic aberration post process,
  76345. */
  76346. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76347. /**
  76348. * ID of the grain post process
  76349. */
  76350. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76351. /**
  76352. * Glow post process which adds a glow to emmisive areas of the image
  76353. */
  76354. _this._glowLayer = null;
  76355. /**
  76356. * Animations which can be used to tweak settings over a period of time
  76357. */
  76358. _this.animations = [];
  76359. _this._imageProcessingConfigurationObserver = null;
  76360. // Values
  76361. _this._sharpenEnabled = false;
  76362. _this._bloomEnabled = false;
  76363. _this._depthOfFieldEnabled = false;
  76364. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76365. _this._fxaaEnabled = false;
  76366. _this._imageProcessingEnabled = true;
  76367. _this._bloomScale = 0.5;
  76368. _this._chromaticAberrationEnabled = false;
  76369. _this._grainEnabled = false;
  76370. _this._buildAllowed = true;
  76371. _this._resizeObserver = null;
  76372. _this._hardwareScaleLevel = 1.0;
  76373. _this._bloomKernel = 64;
  76374. /**
  76375. * Specifies the weight of the bloom in the final rendering
  76376. */
  76377. _this._bloomWeight = 0.15;
  76378. /**
  76379. * Specifies the luma threshold for the area that will be blurred by the bloom
  76380. */
  76381. _this._bloomThreshold = 0.9;
  76382. _this._samples = 1;
  76383. _this._hasCleared = false;
  76384. _this._prevPostProcess = null;
  76385. _this._prevPrevPostProcess = null;
  76386. _this._cameras = cameras || scene.cameras;
  76387. _this._originalCameras = _this._cameras.slice();
  76388. _this._buildAllowed = automaticBuild;
  76389. // Initialize
  76390. _this._scene = scene;
  76391. var caps = _this._scene.getEngine().getCaps();
  76392. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76393. // Misc
  76394. if (_this._hdr) {
  76395. if (caps.textureHalfFloatRender) {
  76396. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76397. }
  76398. else if (caps.textureFloatRender) {
  76399. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76400. }
  76401. }
  76402. else {
  76403. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76404. }
  76405. // Attach
  76406. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76407. var engine = _this._scene.getEngine();
  76408. // Create post processes before hand so they can be modified before enabled.
  76409. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76410. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76411. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76412. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76413. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76414. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76415. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76416. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76417. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76418. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76419. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76420. _this.bloomKernel = _this.bloomKernel;
  76421. });
  76422. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76423. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76424. });
  76425. _this._buildPipeline();
  76426. return _this;
  76427. }
  76428. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76429. get: function () {
  76430. return this._sharpenEnabled;
  76431. },
  76432. /**
  76433. * Enable or disable the sharpen process from the pipeline
  76434. */
  76435. set: function (enabled) {
  76436. if (this._sharpenEnabled === enabled) {
  76437. return;
  76438. }
  76439. this._sharpenEnabled = enabled;
  76440. this._buildPipeline();
  76441. },
  76442. enumerable: true,
  76443. configurable: true
  76444. });
  76445. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76446. /**
  76447. * Specifies the size of the bloom blur kernel, relative to the final output size
  76448. */
  76449. get: function () {
  76450. return this._bloomKernel;
  76451. },
  76452. set: function (value) {
  76453. this._bloomKernel = value;
  76454. this.bloom.kernel = value / this._hardwareScaleLevel;
  76455. },
  76456. enumerable: true,
  76457. configurable: true
  76458. });
  76459. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76460. get: function () {
  76461. return this._bloomWeight;
  76462. },
  76463. /**
  76464. * The strength of the bloom.
  76465. */
  76466. set: function (value) {
  76467. if (this._bloomWeight === value) {
  76468. return;
  76469. }
  76470. this.bloom.weight = value;
  76471. this._bloomWeight = value;
  76472. },
  76473. enumerable: true,
  76474. configurable: true
  76475. });
  76476. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76477. get: function () {
  76478. return this._bloomThreshold;
  76479. },
  76480. /**
  76481. * The strength of the bloom.
  76482. */
  76483. set: function (value) {
  76484. if (this._bloomThreshold === value) {
  76485. return;
  76486. }
  76487. this.bloom.threshold = value;
  76488. this._bloomThreshold = value;
  76489. },
  76490. enumerable: true,
  76491. configurable: true
  76492. });
  76493. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76494. get: function () {
  76495. return this._bloomScale;
  76496. },
  76497. /**
  76498. * The scale of the bloom, lower value will provide better performance.
  76499. */
  76500. set: function (value) {
  76501. if (this._bloomScale === value) {
  76502. return;
  76503. }
  76504. this._bloomScale = value;
  76505. // recreate bloom and dispose old as this setting is not dynamic
  76506. this._rebuildBloom();
  76507. this._buildPipeline();
  76508. },
  76509. enumerable: true,
  76510. configurable: true
  76511. });
  76512. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76513. get: function () {
  76514. return this._bloomEnabled;
  76515. },
  76516. /**
  76517. * Enable or disable the bloom from the pipeline
  76518. */
  76519. set: function (enabled) {
  76520. if (this._bloomEnabled === enabled) {
  76521. return;
  76522. }
  76523. this._bloomEnabled = enabled;
  76524. this._buildPipeline();
  76525. },
  76526. enumerable: true,
  76527. configurable: true
  76528. });
  76529. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76530. // recreate bloom and dispose old as this setting is not dynamic
  76531. var oldBloom = this.bloom;
  76532. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76533. this.bloom.threshold = oldBloom.threshold;
  76534. for (var i = 0; i < this._cameras.length; i++) {
  76535. oldBloom.disposeEffects(this._cameras[i]);
  76536. }
  76537. };
  76538. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76539. /**
  76540. * If the depth of field is enabled.
  76541. */
  76542. get: function () {
  76543. return this._depthOfFieldEnabled;
  76544. },
  76545. set: function (enabled) {
  76546. if (this._depthOfFieldEnabled === enabled) {
  76547. return;
  76548. }
  76549. this._depthOfFieldEnabled = enabled;
  76550. this._buildPipeline();
  76551. },
  76552. enumerable: true,
  76553. configurable: true
  76554. });
  76555. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76556. /**
  76557. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76558. */
  76559. get: function () {
  76560. return this._depthOfFieldBlurLevel;
  76561. },
  76562. set: function (value) {
  76563. if (this._depthOfFieldBlurLevel === value) {
  76564. return;
  76565. }
  76566. this._depthOfFieldBlurLevel = value;
  76567. // recreate dof and dispose old as this setting is not dynamic
  76568. var oldDof = this.depthOfField;
  76569. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76570. this.depthOfField.focalLength = oldDof.focalLength;
  76571. this.depthOfField.focusDistance = oldDof.focusDistance;
  76572. this.depthOfField.fStop = oldDof.fStop;
  76573. this.depthOfField.lensSize = oldDof.lensSize;
  76574. for (var i = 0; i < this._cameras.length; i++) {
  76575. oldDof.disposeEffects(this._cameras[i]);
  76576. }
  76577. this._buildPipeline();
  76578. },
  76579. enumerable: true,
  76580. configurable: true
  76581. });
  76582. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76583. get: function () {
  76584. return this._fxaaEnabled;
  76585. },
  76586. /**
  76587. * If the anti aliasing is enabled.
  76588. */
  76589. set: function (enabled) {
  76590. if (this._fxaaEnabled === enabled) {
  76591. return;
  76592. }
  76593. this._fxaaEnabled = enabled;
  76594. this._buildPipeline();
  76595. },
  76596. enumerable: true,
  76597. configurable: true
  76598. });
  76599. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76600. get: function () {
  76601. return this._samples;
  76602. },
  76603. /**
  76604. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76605. */
  76606. set: function (sampleCount) {
  76607. if (this._samples === sampleCount) {
  76608. return;
  76609. }
  76610. this._samples = sampleCount;
  76611. this._buildPipeline();
  76612. },
  76613. enumerable: true,
  76614. configurable: true
  76615. });
  76616. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76617. get: function () {
  76618. return this._imageProcessingEnabled;
  76619. },
  76620. /**
  76621. * If image processing is enabled.
  76622. */
  76623. set: function (enabled) {
  76624. if (this._imageProcessingEnabled === enabled) {
  76625. return;
  76626. }
  76627. this._imageProcessingEnabled = enabled;
  76628. this._buildPipeline();
  76629. },
  76630. enumerable: true,
  76631. configurable: true
  76632. });
  76633. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76634. get: function () {
  76635. return this._glowLayer == null;
  76636. },
  76637. /**
  76638. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76639. */
  76640. set: function (enabled) {
  76641. if (enabled && !this._glowLayer) {
  76642. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76643. }
  76644. else if (!enabled && this._glowLayer) {
  76645. this._glowLayer.dispose();
  76646. this._glowLayer = null;
  76647. }
  76648. },
  76649. enumerable: true,
  76650. configurable: true
  76651. });
  76652. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76653. get: function () {
  76654. return this._chromaticAberrationEnabled;
  76655. },
  76656. /**
  76657. * Enable or disable the chromaticAberration process from the pipeline
  76658. */
  76659. set: function (enabled) {
  76660. if (this._chromaticAberrationEnabled === enabled) {
  76661. return;
  76662. }
  76663. this._chromaticAberrationEnabled = enabled;
  76664. this._buildPipeline();
  76665. },
  76666. enumerable: true,
  76667. configurable: true
  76668. });
  76669. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76670. get: function () {
  76671. return this._grainEnabled;
  76672. },
  76673. /**
  76674. * Enable or disable the grain process from the pipeline
  76675. */
  76676. set: function (enabled) {
  76677. if (this._grainEnabled === enabled) {
  76678. return;
  76679. }
  76680. this._grainEnabled = enabled;
  76681. this._buildPipeline();
  76682. },
  76683. enumerable: true,
  76684. configurable: true
  76685. });
  76686. /**
  76687. * Force the compilation of the entire pipeline.
  76688. */
  76689. DefaultRenderingPipeline.prototype.prepare = function () {
  76690. var previousState = this._buildAllowed;
  76691. this._buildAllowed = true;
  76692. this._buildPipeline();
  76693. this._buildAllowed = previousState;
  76694. };
  76695. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76696. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76697. if (this._hasCleared) {
  76698. postProcess.autoClear = false;
  76699. }
  76700. else {
  76701. postProcess.autoClear = true;
  76702. this._scene.autoClear = false;
  76703. this._hasCleared = true;
  76704. }
  76705. if (!skipTextureSharing) {
  76706. if (this._prevPrevPostProcess) {
  76707. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76708. }
  76709. else {
  76710. postProcess.useOwnOutput();
  76711. }
  76712. if (this._prevPostProcess) {
  76713. this._prevPrevPostProcess = this._prevPostProcess;
  76714. }
  76715. this._prevPostProcess = postProcess;
  76716. }
  76717. };
  76718. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76719. var _this = this;
  76720. if (!this._buildAllowed) {
  76721. return;
  76722. }
  76723. this._scene.autoClear = true;
  76724. var engine = this._scene.getEngine();
  76725. this._disposePostProcesses();
  76726. if (this._cameras !== null) {
  76727. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76728. // get back cameras to be used to reattach pipeline
  76729. this._cameras = this._originalCameras.slice();
  76730. }
  76731. this._reset();
  76732. this._prevPostProcess = null;
  76733. this._prevPrevPostProcess = null;
  76734. this._hasCleared = false;
  76735. if (this.depthOfFieldEnabled) {
  76736. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76737. this.depthOfField.depthTexture = depthTexture;
  76738. if (!this.depthOfField._isReady()) {
  76739. this.depthOfField._updateEffects();
  76740. }
  76741. this.addEffect(this.depthOfField);
  76742. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76743. }
  76744. if (this.bloomEnabled) {
  76745. if (!this.bloom._isReady()) {
  76746. this.bloom._updateEffects();
  76747. }
  76748. this.addEffect(this.bloom);
  76749. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76750. }
  76751. if (this._imageProcessingEnabled) {
  76752. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76753. if (this._hdr) {
  76754. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76755. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76756. }
  76757. else {
  76758. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76759. }
  76760. }
  76761. if (this.sharpenEnabled) {
  76762. if (!this.sharpen.isReady()) {
  76763. this.sharpen.updateEffect();
  76764. }
  76765. this.addEffect(this._sharpenEffect);
  76766. this._setAutoClearAndTextureSharing(this.sharpen);
  76767. }
  76768. if (this.grainEnabled) {
  76769. if (!this.grain.isReady()) {
  76770. this.grain.updateEffect();
  76771. }
  76772. this.addEffect(this._grainEffect);
  76773. this._setAutoClearAndTextureSharing(this.grain);
  76774. }
  76775. if (this.chromaticAberrationEnabled) {
  76776. if (!this.chromaticAberration.isReady()) {
  76777. this.chromaticAberration.updateEffect();
  76778. }
  76779. this.addEffect(this._chromaticAberrationEffect);
  76780. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76781. }
  76782. if (this.fxaaEnabled) {
  76783. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76784. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76785. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76786. }
  76787. if (this._cameras !== null) {
  76788. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76789. }
  76790. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76791. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76792. }
  76793. };
  76794. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76795. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76796. for (var i = 0; i < this._cameras.length; i++) {
  76797. var camera = this._cameras[i];
  76798. if (this.imageProcessing) {
  76799. this.imageProcessing.dispose(camera);
  76800. }
  76801. if (this.fxaa) {
  76802. this.fxaa.dispose(camera);
  76803. }
  76804. // These are created in the constructor and should not be disposed on every pipeline change
  76805. if (disposeNonRecreated) {
  76806. if (this.sharpen) {
  76807. this.sharpen.dispose(camera);
  76808. }
  76809. if (this.depthOfField) {
  76810. this.depthOfField.disposeEffects(camera);
  76811. }
  76812. if (this.bloom) {
  76813. this.bloom.disposeEffects(camera);
  76814. }
  76815. if (this.chromaticAberration) {
  76816. this.chromaticAberration.dispose(camera);
  76817. }
  76818. if (this.grain) {
  76819. this.grain.dispose(camera);
  76820. }
  76821. if (this._glowLayer) {
  76822. this._glowLayer.dispose();
  76823. }
  76824. }
  76825. }
  76826. this.imageProcessing = null;
  76827. this.fxaa = null;
  76828. if (disposeNonRecreated) {
  76829. this.sharpen = null;
  76830. this._sharpenEffect = null;
  76831. this.depthOfField = null;
  76832. this.bloom = null;
  76833. this.chromaticAberration = null;
  76834. this._chromaticAberrationEffect = null;
  76835. this.grain = null;
  76836. this._grainEffect = null;
  76837. this._glowLayer = null;
  76838. }
  76839. };
  76840. /**
  76841. * Dispose of the pipeline and stop all post processes
  76842. */
  76843. DefaultRenderingPipeline.prototype.dispose = function () {
  76844. this._disposePostProcesses(true);
  76845. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76846. this._scene.autoClear = true;
  76847. if (this._resizeObserver) {
  76848. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76849. this._resizeObserver = null;
  76850. }
  76851. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76852. _super.prototype.dispose.call(this);
  76853. };
  76854. /**
  76855. * Serialize the rendering pipeline (Used when exporting)
  76856. * @returns the serialized object
  76857. */
  76858. DefaultRenderingPipeline.prototype.serialize = function () {
  76859. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76860. serializationObject.customType = "DefaultRenderingPipeline";
  76861. return serializationObject;
  76862. };
  76863. /**
  76864. * Parse the serialized pipeline
  76865. * @param source Source pipeline.
  76866. * @param scene The scene to load the pipeline to.
  76867. * @param rootUrl The URL of the serialized pipeline.
  76868. * @returns An instantiated pipeline from the serialized object.
  76869. */
  76870. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76871. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76872. };
  76873. __decorate([
  76874. BABYLON.serialize()
  76875. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76876. __decorate([
  76877. BABYLON.serialize()
  76878. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76879. __decorate([
  76880. BABYLON.serialize()
  76881. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76882. __decorate([
  76883. BABYLON.serialize()
  76884. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76885. __decorate([
  76886. BABYLON.serialize()
  76887. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76888. __decorate([
  76889. BABYLON.serialize()
  76890. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76891. __decorate([
  76892. BABYLON.serialize()
  76893. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76894. __decorate([
  76895. BABYLON.serialize()
  76896. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76897. __decorate([
  76898. BABYLON.serialize()
  76899. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76900. __decorate([
  76901. BABYLON.serialize()
  76902. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76903. __decorate([
  76904. BABYLON.serialize()
  76905. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76906. __decorate([
  76907. BABYLON.serialize()
  76908. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76909. __decorate([
  76910. BABYLON.serialize()
  76911. ], DefaultRenderingPipeline.prototype, "samples", null);
  76912. __decorate([
  76913. BABYLON.serialize()
  76914. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76915. __decorate([
  76916. BABYLON.serialize()
  76917. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76918. __decorate([
  76919. BABYLON.serialize()
  76920. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76921. __decorate([
  76922. BABYLON.serialize()
  76923. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76924. return DefaultRenderingPipeline;
  76925. }(BABYLON.PostProcessRenderPipeline));
  76926. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76927. })(BABYLON || (BABYLON = {}));
  76928. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76929. var BABYLON;
  76930. (function (BABYLON) {
  76931. /**
  76932. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76933. */
  76934. var GeometryBufferRenderer = /** @class */ (function () {
  76935. /**
  76936. * Creates a new G Buffer for the scene
  76937. * @param scene The scene the buffer belongs to
  76938. * @param ratio How big is the buffer related to the main canvas.
  76939. */
  76940. function GeometryBufferRenderer(scene, ratio) {
  76941. if (ratio === void 0) { ratio = 1; }
  76942. this._enablePosition = false;
  76943. this._scene = scene;
  76944. this._ratio = ratio;
  76945. // Render target
  76946. this._createRenderTargets();
  76947. }
  76948. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76949. /**
  76950. * Set the render list (meshes to be rendered) used in the G buffer.
  76951. */
  76952. set: function (meshes) {
  76953. this._multiRenderTarget.renderList = meshes;
  76954. },
  76955. enumerable: true,
  76956. configurable: true
  76957. });
  76958. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76959. /**
  76960. * Gets wether or not G buffer are supported by the running hardware.
  76961. * This requires draw buffer supports
  76962. */
  76963. get: function () {
  76964. return this._multiRenderTarget.isSupported;
  76965. },
  76966. enumerable: true,
  76967. configurable: true
  76968. });
  76969. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76970. /**
  76971. * Gets wether or not position are enabled for the G buffer.
  76972. */
  76973. get: function () {
  76974. return this._enablePosition;
  76975. },
  76976. /**
  76977. * Sets wether or not position are enabled for the G buffer.
  76978. */
  76979. set: function (enable) {
  76980. this._enablePosition = enable;
  76981. this.dispose();
  76982. this._createRenderTargets();
  76983. },
  76984. enumerable: true,
  76985. configurable: true
  76986. });
  76987. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76988. /**
  76989. * Gets the scene associated with the buffer.
  76990. */
  76991. get: function () {
  76992. return this._scene;
  76993. },
  76994. enumerable: true,
  76995. configurable: true
  76996. });
  76997. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76998. /**
  76999. * Gets the ratio used by the buffer during its creation.
  77000. * How big is the buffer related to the main canvas.
  77001. */
  77002. get: function () {
  77003. return this._ratio;
  77004. },
  77005. enumerable: true,
  77006. configurable: true
  77007. });
  77008. /**
  77009. * Checks wether everything is ready to render a submesh to the G buffer.
  77010. * @param subMesh the submesh to check readiness for
  77011. * @param useInstances is the mesh drawn using instance or not
  77012. * @returns true if ready otherwise false
  77013. */
  77014. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77015. var material = subMesh.getMaterial();
  77016. if (material && material.disableDepthWrite) {
  77017. return false;
  77018. }
  77019. var defines = [];
  77020. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77021. var mesh = subMesh.getMesh();
  77022. // Alpha test
  77023. if (material && material.needAlphaTesting()) {
  77024. defines.push("#define ALPHATEST");
  77025. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77026. attribs.push(BABYLON.VertexBuffer.UVKind);
  77027. defines.push("#define UV1");
  77028. }
  77029. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77030. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77031. defines.push("#define UV2");
  77032. }
  77033. }
  77034. // Buffers
  77035. if (this._enablePosition) {
  77036. defines.push("#define POSITION");
  77037. }
  77038. // Bones
  77039. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77040. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77041. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77042. if (mesh.numBoneInfluencers > 4) {
  77043. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77044. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77045. }
  77046. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77047. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77048. }
  77049. else {
  77050. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77051. }
  77052. // Instances
  77053. if (useInstances) {
  77054. defines.push("#define INSTANCES");
  77055. attribs.push("world0");
  77056. attribs.push("world1");
  77057. attribs.push("world2");
  77058. attribs.push("world3");
  77059. }
  77060. // Get correct effect
  77061. var join = defines.join("\n");
  77062. if (this._cachedDefines !== join) {
  77063. this._cachedDefines = join;
  77064. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77065. }
  77066. return this._effect.isReady();
  77067. };
  77068. /**
  77069. * Gets the current underlying G Buffer.
  77070. * @returns the buffer
  77071. */
  77072. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77073. return this._multiRenderTarget;
  77074. };
  77075. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77076. /**
  77077. * Gets the number of samples used to render the buffer (anti aliasing).
  77078. */
  77079. get: function () {
  77080. return this._multiRenderTarget.samples;
  77081. },
  77082. /**
  77083. * Sets the number of samples used to render the buffer (anti aliasing).
  77084. */
  77085. set: function (value) {
  77086. this._multiRenderTarget.samples = value;
  77087. },
  77088. enumerable: true,
  77089. configurable: true
  77090. });
  77091. /**
  77092. * Disposes the renderer and frees up associated resources.
  77093. */
  77094. GeometryBufferRenderer.prototype.dispose = function () {
  77095. this.getGBuffer().dispose();
  77096. };
  77097. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77098. var _this = this;
  77099. var engine = this._scene.getEngine();
  77100. var count = this._enablePosition ? 3 : 2;
  77101. 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 });
  77102. if (!this.isSupported) {
  77103. return;
  77104. }
  77105. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77106. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77107. this._multiRenderTarget.refreshRate = 1;
  77108. this._multiRenderTarget.renderParticles = false;
  77109. this._multiRenderTarget.renderList = null;
  77110. // set default depth value to 1.0 (far away)
  77111. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77112. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77113. });
  77114. // Custom render function
  77115. var renderSubMesh = function (subMesh) {
  77116. var mesh = subMesh.getRenderingMesh();
  77117. var scene = _this._scene;
  77118. var engine = scene.getEngine();
  77119. var material = subMesh.getMaterial();
  77120. if (!material) {
  77121. return;
  77122. }
  77123. // Culling
  77124. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77125. // Managing instances
  77126. var batch = mesh._getInstancesRenderList(subMesh._id);
  77127. if (batch.mustReturn) {
  77128. return;
  77129. }
  77130. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77131. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77132. engine.enableEffect(_this._effect);
  77133. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77134. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77135. _this._effect.setMatrix("view", scene.getViewMatrix());
  77136. // Alpha test
  77137. if (material && material.needAlphaTesting()) {
  77138. var alphaTexture = material.getAlphaTestTexture();
  77139. if (alphaTexture) {
  77140. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77141. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77142. }
  77143. }
  77144. // Bones
  77145. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77146. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77147. }
  77148. // Draw
  77149. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77150. }
  77151. };
  77152. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77153. var index;
  77154. if (depthOnlySubMeshes.length) {
  77155. engine.setColorWrite(false);
  77156. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77157. renderSubMesh(depthOnlySubMeshes.data[index]);
  77158. }
  77159. engine.setColorWrite(true);
  77160. }
  77161. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77162. renderSubMesh(opaqueSubMeshes.data[index]);
  77163. }
  77164. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77165. renderSubMesh(alphaTestSubMeshes.data[index]);
  77166. }
  77167. };
  77168. };
  77169. return GeometryBufferRenderer;
  77170. }());
  77171. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77172. })(BABYLON || (BABYLON = {}));
  77173. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77174. var BABYLON;
  77175. (function (BABYLON) {
  77176. var RefractionPostProcess = /** @class */ (function (_super) {
  77177. __extends(RefractionPostProcess, _super);
  77178. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77179. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77180. _this.color = color;
  77181. _this.depth = depth;
  77182. _this.colorLevel = colorLevel;
  77183. _this._ownRefractionTexture = true;
  77184. _this.onActivateObservable.add(function (cam) {
  77185. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77186. });
  77187. _this.onApplyObservable.add(function (effect) {
  77188. effect.setColor3("baseColor", _this.color);
  77189. effect.setFloat("depth", _this.depth);
  77190. effect.setFloat("colorLevel", _this.colorLevel);
  77191. effect.setTexture("refractionSampler", _this._refTexture);
  77192. });
  77193. return _this;
  77194. }
  77195. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77196. /**
  77197. * Gets or sets the refraction texture
  77198. * Please note that you are responsible for disposing the texture if you set it manually
  77199. */
  77200. get: function () {
  77201. return this._refTexture;
  77202. },
  77203. set: function (value) {
  77204. if (this._refTexture && this._ownRefractionTexture) {
  77205. this._refTexture.dispose();
  77206. }
  77207. this._refTexture = value;
  77208. this._ownRefractionTexture = false;
  77209. },
  77210. enumerable: true,
  77211. configurable: true
  77212. });
  77213. // Methods
  77214. RefractionPostProcess.prototype.dispose = function (camera) {
  77215. if (this._refTexture && this._ownRefractionTexture) {
  77216. this._refTexture.dispose();
  77217. this._refTexture = null;
  77218. }
  77219. _super.prototype.dispose.call(this, camera);
  77220. };
  77221. return RefractionPostProcess;
  77222. }(BABYLON.PostProcess));
  77223. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77224. })(BABYLON || (BABYLON = {}));
  77225. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77226. var BABYLON;
  77227. (function (BABYLON) {
  77228. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77229. __extends(BlackAndWhitePostProcess, _super);
  77230. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77231. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77232. _this.degree = 1;
  77233. _this.onApplyObservable.add(function (effect) {
  77234. effect.setFloat("degree", _this.degree);
  77235. });
  77236. return _this;
  77237. }
  77238. return BlackAndWhitePostProcess;
  77239. }(BABYLON.PostProcess));
  77240. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77241. })(BABYLON || (BABYLON = {}));
  77242. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77243. var BABYLON;
  77244. (function (BABYLON) {
  77245. /**
  77246. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77247. * input texture to perform effects such as edge detection or sharpening
  77248. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77249. */
  77250. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77251. __extends(ConvolutionPostProcess, _super);
  77252. /**
  77253. * Creates a new instance ConvolutionPostProcess
  77254. * @param name The name of the effect.
  77255. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77256. * @param options The required width/height ratio to downsize to before computing the render pass.
  77257. * @param camera The camera to apply the render pass to.
  77258. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77259. * @param engine The engine which the post process will be applied. (default: current engine)
  77260. * @param reusable If the post process can be reused on the same frame. (default: false)
  77261. * @param textureType Type of textures used when performing the post process. (default: 0)
  77262. */
  77263. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77264. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77265. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77266. _this.kernel = kernel;
  77267. _this.onApply = function (effect) {
  77268. effect.setFloat2("screenSize", _this.width, _this.height);
  77269. effect.setArray("kernel", _this.kernel);
  77270. };
  77271. return _this;
  77272. }
  77273. // Statics
  77274. /**
  77275. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77276. */
  77277. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77278. /**
  77279. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77280. */
  77281. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77282. /**
  77283. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77284. */
  77285. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77286. /**
  77287. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77288. */
  77289. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77290. /**
  77291. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77292. */
  77293. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77294. /**
  77295. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77296. */
  77297. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77298. return ConvolutionPostProcess;
  77299. }(BABYLON.PostProcess));
  77300. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77301. })(BABYLON || (BABYLON = {}));
  77302. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77303. var BABYLON;
  77304. (function (BABYLON) {
  77305. var FilterPostProcess = /** @class */ (function (_super) {
  77306. __extends(FilterPostProcess, _super);
  77307. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77308. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77309. _this.kernelMatrix = kernelMatrix;
  77310. _this.onApply = function (effect) {
  77311. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77312. };
  77313. return _this;
  77314. }
  77315. return FilterPostProcess;
  77316. }(BABYLON.PostProcess));
  77317. BABYLON.FilterPostProcess = FilterPostProcess;
  77318. })(BABYLON || (BABYLON = {}));
  77319. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77320. var BABYLON;
  77321. (function (BABYLON) {
  77322. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77323. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77324. __extends(VolumetricLightScatteringPostProcess, _super);
  77325. /**
  77326. * @constructor
  77327. * @param {string} name - The post-process name
  77328. * @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)
  77329. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77330. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77331. * @param {number} samples - The post-process quality, default 100
  77332. * @param {number} samplingMode - The post-process filtering mode
  77333. * @param {BABYLON.Engine} engine - The babylon engine
  77334. * @param {boolean} reusable - If the post-process is reusable
  77335. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77336. */
  77337. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77338. if (samples === void 0) { samples = 100; }
  77339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77340. 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;
  77341. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77342. /**
  77343. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77344. */
  77345. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77346. /**
  77347. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77348. */
  77349. _this.useCustomMeshPosition = false;
  77350. /**
  77351. * If the post-process should inverse the light scattering direction
  77352. */
  77353. _this.invert = true;
  77354. /**
  77355. * Array containing the excluded meshes not rendered in the internal pass
  77356. */
  77357. _this.excludedMeshes = new Array();
  77358. /**
  77359. * Controls the overall intensity of the post-process
  77360. */
  77361. _this.exposure = 0.3;
  77362. /**
  77363. * Dissipates each sample's contribution in range [0, 1]
  77364. */
  77365. _this.decay = 0.96815;
  77366. /**
  77367. * Controls the overall intensity of each sample
  77368. */
  77369. _this.weight = 0.58767;
  77370. /**
  77371. * Controls the density of each sample
  77372. */
  77373. _this.density = 0.926;
  77374. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77375. engine = scene.getEngine();
  77376. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77377. // Configure mesh
  77378. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77379. // Configure
  77380. _this._createPass(scene, ratio.passRatio || ratio);
  77381. _this.onActivate = function (camera) {
  77382. if (!_this.isSupported) {
  77383. _this.dispose(camera);
  77384. }
  77385. _this.onActivate = null;
  77386. };
  77387. _this.onApplyObservable.add(function (effect) {
  77388. _this._updateMeshScreenCoordinates(scene);
  77389. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77390. effect.setFloat("exposure", _this.exposure);
  77391. effect.setFloat("decay", _this.decay);
  77392. effect.setFloat("weight", _this.weight);
  77393. effect.setFloat("density", _this.density);
  77394. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77395. });
  77396. return _this;
  77397. }
  77398. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77399. get: function () {
  77400. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77401. return false;
  77402. },
  77403. set: function (useDiffuseColor) {
  77404. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77405. },
  77406. enumerable: true,
  77407. configurable: true
  77408. });
  77409. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77410. return "VolumetricLightScatteringPostProcess";
  77411. };
  77412. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77413. var mesh = subMesh.getMesh();
  77414. // Render this.mesh as default
  77415. if (mesh === this.mesh && mesh.material) {
  77416. return mesh.material.isReady(mesh);
  77417. }
  77418. var defines = [];
  77419. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77420. var material = subMesh.getMaterial();
  77421. // Alpha test
  77422. if (material) {
  77423. if (material.needAlphaTesting()) {
  77424. defines.push("#define ALPHATEST");
  77425. }
  77426. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77427. attribs.push(BABYLON.VertexBuffer.UVKind);
  77428. defines.push("#define UV1");
  77429. }
  77430. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77431. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77432. defines.push("#define UV2");
  77433. }
  77434. }
  77435. // Bones
  77436. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77437. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77438. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77439. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77440. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77441. }
  77442. else {
  77443. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77444. }
  77445. // Instances
  77446. if (useInstances) {
  77447. defines.push("#define INSTANCES");
  77448. attribs.push("world0");
  77449. attribs.push("world1");
  77450. attribs.push("world2");
  77451. attribs.push("world3");
  77452. }
  77453. // Get correct effect
  77454. var join = defines.join("\n");
  77455. if (this._cachedDefines !== join) {
  77456. this._cachedDefines = join;
  77457. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77458. }
  77459. return this._volumetricLightScatteringPass.isReady();
  77460. };
  77461. /**
  77462. * Sets the new light position for light scattering effect
  77463. * @param {BABYLON.Vector3} The new custom light position
  77464. */
  77465. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77466. this.customMeshPosition = position;
  77467. };
  77468. /**
  77469. * Returns the light position for light scattering effect
  77470. * @return {BABYLON.Vector3} The custom light position
  77471. */
  77472. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77473. return this.customMeshPosition;
  77474. };
  77475. /**
  77476. * Disposes the internal assets and detaches the post-process from the camera
  77477. */
  77478. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77479. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77480. if (rttIndex !== -1) {
  77481. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77482. }
  77483. this._volumetricLightScatteringRTT.dispose();
  77484. _super.prototype.dispose.call(this, camera);
  77485. };
  77486. /**
  77487. * Returns the render target texture used by the post-process
  77488. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77489. */
  77490. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77491. return this._volumetricLightScatteringRTT;
  77492. };
  77493. // Private methods
  77494. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77495. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77496. return true;
  77497. }
  77498. return false;
  77499. };
  77500. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77501. var _this = this;
  77502. var engine = scene.getEngine();
  77503. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77504. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77505. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77506. this._volumetricLightScatteringRTT.renderList = null;
  77507. this._volumetricLightScatteringRTT.renderParticles = false;
  77508. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77509. var camera = this.getCamera();
  77510. if (camera) {
  77511. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77512. }
  77513. else {
  77514. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77515. }
  77516. // Custom render function for submeshes
  77517. var renderSubMesh = function (subMesh) {
  77518. var mesh = subMesh.getRenderingMesh();
  77519. if (_this._meshExcluded(mesh)) {
  77520. return;
  77521. }
  77522. var material = subMesh.getMaterial();
  77523. if (!material) {
  77524. return;
  77525. }
  77526. var scene = mesh.getScene();
  77527. var engine = scene.getEngine();
  77528. // Culling
  77529. engine.setState(material.backFaceCulling);
  77530. // Managing instances
  77531. var batch = mesh._getInstancesRenderList(subMesh._id);
  77532. if (batch.mustReturn) {
  77533. return;
  77534. }
  77535. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77536. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77537. var effect = _this._volumetricLightScatteringPass;
  77538. if (mesh === _this.mesh) {
  77539. if (subMesh.effect) {
  77540. effect = subMesh.effect;
  77541. }
  77542. else {
  77543. effect = material.getEffect();
  77544. }
  77545. }
  77546. engine.enableEffect(effect);
  77547. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77548. if (mesh === _this.mesh) {
  77549. material.bind(mesh.getWorldMatrix(), mesh);
  77550. }
  77551. else {
  77552. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77553. // Alpha test
  77554. if (material && material.needAlphaTesting()) {
  77555. var alphaTexture = material.getAlphaTestTexture();
  77556. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77557. if (alphaTexture) {
  77558. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77559. }
  77560. }
  77561. // Bones
  77562. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77563. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77564. }
  77565. }
  77566. // Draw
  77567. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77568. }
  77569. };
  77570. // Render target texture callbacks
  77571. var savedSceneClearColor;
  77572. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77573. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77574. savedSceneClearColor = scene.clearColor;
  77575. scene.clearColor = sceneClearColor;
  77576. });
  77577. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77578. scene.clearColor = savedSceneClearColor;
  77579. });
  77580. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77581. var engine = scene.getEngine();
  77582. var index;
  77583. if (depthOnlySubMeshes.length) {
  77584. engine.setColorWrite(false);
  77585. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77586. renderSubMesh(depthOnlySubMeshes.data[index]);
  77587. }
  77588. engine.setColorWrite(true);
  77589. }
  77590. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77591. renderSubMesh(opaqueSubMeshes.data[index]);
  77592. }
  77593. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77594. renderSubMesh(alphaTestSubMeshes.data[index]);
  77595. }
  77596. if (transparentSubMeshes.length) {
  77597. // Sort sub meshes
  77598. for (index = 0; index < transparentSubMeshes.length; index++) {
  77599. var submesh = transparentSubMeshes.data[index];
  77600. var boundingInfo = submesh.getBoundingInfo();
  77601. if (boundingInfo && scene.activeCamera) {
  77602. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77603. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77604. }
  77605. }
  77606. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77607. sortedArray.sort(function (a, b) {
  77608. // Alpha index first
  77609. if (a._alphaIndex > b._alphaIndex) {
  77610. return 1;
  77611. }
  77612. if (a._alphaIndex < b._alphaIndex) {
  77613. return -1;
  77614. }
  77615. // Then distance to camera
  77616. if (a._distanceToCamera < b._distanceToCamera) {
  77617. return 1;
  77618. }
  77619. if (a._distanceToCamera > b._distanceToCamera) {
  77620. return -1;
  77621. }
  77622. return 0;
  77623. });
  77624. // Render sub meshes
  77625. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77626. for (index = 0; index < sortedArray.length; index++) {
  77627. renderSubMesh(sortedArray[index]);
  77628. }
  77629. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77630. }
  77631. };
  77632. };
  77633. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77634. var transform = scene.getTransformMatrix();
  77635. var meshPosition;
  77636. if (this.useCustomMeshPosition) {
  77637. meshPosition = this.customMeshPosition;
  77638. }
  77639. else if (this.attachedNode) {
  77640. meshPosition = this.attachedNode.position;
  77641. }
  77642. else {
  77643. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77644. }
  77645. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77646. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77647. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77648. if (this.invert)
  77649. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77650. };
  77651. // Static methods
  77652. /**
  77653. * Creates a default mesh for the Volumeric Light Scattering post-process
  77654. * @param {string} The mesh name
  77655. * @param {BABYLON.Scene} The scene where to create the mesh
  77656. * @return {BABYLON.Mesh} the default mesh
  77657. */
  77658. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77659. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77660. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77661. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77662. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77663. mesh.material = material;
  77664. return mesh;
  77665. };
  77666. __decorate([
  77667. BABYLON.serializeAsVector3()
  77668. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77669. __decorate([
  77670. BABYLON.serialize()
  77671. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77672. __decorate([
  77673. BABYLON.serialize()
  77674. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77675. __decorate([
  77676. BABYLON.serializeAsMeshReference()
  77677. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77678. __decorate([
  77679. BABYLON.serialize()
  77680. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77681. __decorate([
  77682. BABYLON.serialize()
  77683. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77684. __decorate([
  77685. BABYLON.serialize()
  77686. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77687. __decorate([
  77688. BABYLON.serialize()
  77689. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77690. __decorate([
  77691. BABYLON.serialize()
  77692. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77693. return VolumetricLightScatteringPostProcess;
  77694. }(BABYLON.PostProcess));
  77695. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77696. })(BABYLON || (BABYLON = {}));
  77697. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77698. //
  77699. // This post-process allows the modification of rendered colors by using
  77700. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77701. //
  77702. // The object needs to be provided an url to a texture containing the color
  77703. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77704. // Use an image editing software to tweak the LUT to match your needs.
  77705. //
  77706. // For an example of a color LUT, see here:
  77707. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77708. // For explanations on color grading, see here:
  77709. // http://udn.epicgames.com/Three/ColorGrading.html
  77710. //
  77711. var BABYLON;
  77712. (function (BABYLON) {
  77713. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77714. __extends(ColorCorrectionPostProcess, _super);
  77715. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77716. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77717. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77718. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77719. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77720. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77721. _this.onApply = function (effect) {
  77722. effect.setTexture("colorTable", _this._colorTableTexture);
  77723. };
  77724. return _this;
  77725. }
  77726. return ColorCorrectionPostProcess;
  77727. }(BABYLON.PostProcess));
  77728. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77729. })(BABYLON || (BABYLON = {}));
  77730. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77731. var BABYLON;
  77732. (function (BABYLON) {
  77733. /** Defines operator used for tonemapping */
  77734. var TonemappingOperator;
  77735. (function (TonemappingOperator) {
  77736. /** Hable */
  77737. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77738. /** Reinhard */
  77739. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77740. /** HejiDawson */
  77741. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77742. /** Photographic */
  77743. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77744. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77745. ;
  77746. /**
  77747. * Defines a post process to apply tone mapping
  77748. */
  77749. var TonemapPostProcess = /** @class */ (function (_super) {
  77750. __extends(TonemapPostProcess, _super);
  77751. /**
  77752. * Creates a new TonemapPostProcess
  77753. * @param name defines the name of the postprocess
  77754. * @param _operator defines the operator to use
  77755. * @param exposureAdjustment defines the required exposure adjustement
  77756. * @param camera defines the camera to use (can be null)
  77757. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77758. * @param engine defines the hosting engine (can be ignore if camera is set)
  77759. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77760. */
  77761. function TonemapPostProcess(name, _operator,
  77762. /** Defines the required exposure adjustement */
  77763. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77765. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77766. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77767. _this._operator = _operator;
  77768. _this.exposureAdjustment = exposureAdjustment;
  77769. var defines = "#define ";
  77770. if (_this._operator === TonemappingOperator.Hable)
  77771. defines += "HABLE_TONEMAPPING";
  77772. else if (_this._operator === TonemappingOperator.Reinhard)
  77773. defines += "REINHARD_TONEMAPPING";
  77774. else if (_this._operator === TonemappingOperator.HejiDawson)
  77775. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77776. else if (_this._operator === TonemappingOperator.Photographic)
  77777. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77778. //sadly a second call to create the effect.
  77779. _this.updateEffect(defines);
  77780. _this.onApply = function (effect) {
  77781. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77782. };
  77783. return _this;
  77784. }
  77785. return TonemapPostProcess;
  77786. }(BABYLON.PostProcess));
  77787. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77788. })(BABYLON || (BABYLON = {}));
  77789. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77790. var BABYLON;
  77791. (function (BABYLON) {
  77792. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77793. __extends(DisplayPassPostProcess, _super);
  77794. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77795. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77796. }
  77797. return DisplayPassPostProcess;
  77798. }(BABYLON.PostProcess));
  77799. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77800. })(BABYLON || (BABYLON = {}));
  77801. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77802. var BABYLON;
  77803. (function (BABYLON) {
  77804. var HighlightsPostProcess = /** @class */ (function (_super) {
  77805. __extends(HighlightsPostProcess, _super);
  77806. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77807. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77808. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77809. }
  77810. return HighlightsPostProcess;
  77811. }(BABYLON.PostProcess));
  77812. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77813. })(BABYLON || (BABYLON = {}));
  77814. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77815. var BABYLON;
  77816. (function (BABYLON) {
  77817. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77818. __extends(ImageProcessingPostProcess, _super);
  77819. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77820. if (camera === void 0) { camera = null; }
  77821. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77822. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77823. _this._fromLinearSpace = true;
  77824. /**
  77825. * Defines cache preventing GC.
  77826. */
  77827. _this._defines = {
  77828. IMAGEPROCESSING: false,
  77829. VIGNETTE: false,
  77830. VIGNETTEBLENDMODEMULTIPLY: false,
  77831. VIGNETTEBLENDMODEOPAQUE: false,
  77832. TONEMAPPING: false,
  77833. CONTRAST: false,
  77834. COLORCURVES: false,
  77835. COLORGRADING: false,
  77836. COLORGRADING3D: false,
  77837. FROMLINEARSPACE: false,
  77838. SAMPLER3DGREENDEPTH: false,
  77839. SAMPLER3DBGRMAP: false,
  77840. IMAGEPROCESSINGPOSTPROCESS: false,
  77841. EXPOSURE: false,
  77842. };
  77843. // Setup the configuration as forced by the constructor. This would then not force the
  77844. // scene materials output in linear space and let untouched the default forward pass.
  77845. if (imageProcessingConfiguration) {
  77846. imageProcessingConfiguration.applyByPostProcess = true;
  77847. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77848. // This will cause the shader to be compiled
  77849. _this.fromLinearSpace = false;
  77850. }
  77851. // Setup the default processing configuration to the scene.
  77852. else {
  77853. _this._attachImageProcessingConfiguration(null, true);
  77854. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77855. }
  77856. _this.onApply = function (effect) {
  77857. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77858. };
  77859. return _this;
  77860. }
  77861. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77862. /**
  77863. * Gets the image processing configuration used either in this material.
  77864. */
  77865. get: function () {
  77866. return this._imageProcessingConfiguration;
  77867. },
  77868. /**
  77869. * Sets the Default image processing configuration used either in the this material.
  77870. *
  77871. * If sets to null, the scene one is in use.
  77872. */
  77873. set: function (value) {
  77874. this._attachImageProcessingConfiguration(value);
  77875. },
  77876. enumerable: true,
  77877. configurable: true
  77878. });
  77879. /**
  77880. * Attaches a new image processing configuration to the PBR Material.
  77881. * @param configuration
  77882. */
  77883. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77884. var _this = this;
  77885. if (doNotBuild === void 0) { doNotBuild = false; }
  77886. if (configuration === this._imageProcessingConfiguration) {
  77887. return;
  77888. }
  77889. // Detaches observer.
  77890. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77891. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77892. }
  77893. // Pick the scene configuration if needed.
  77894. if (!configuration) {
  77895. var scene = null;
  77896. var engine = this.getEngine();
  77897. var camera = this.getCamera();
  77898. if (camera) {
  77899. scene = camera.getScene();
  77900. }
  77901. else if (engine && engine.scenes) {
  77902. var scenes = engine.scenes;
  77903. scene = scenes[scenes.length - 1];
  77904. }
  77905. else {
  77906. scene = BABYLON.Engine.LastCreatedScene;
  77907. }
  77908. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77909. }
  77910. else {
  77911. this._imageProcessingConfiguration = configuration;
  77912. }
  77913. // Attaches observer.
  77914. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77915. _this._updateParameters();
  77916. });
  77917. // Ensure the effect will be rebuilt.
  77918. if (!doNotBuild) {
  77919. this._updateParameters();
  77920. }
  77921. };
  77922. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77923. /**
  77924. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77925. */
  77926. get: function () {
  77927. return this.imageProcessingConfiguration.colorCurves;
  77928. },
  77929. /**
  77930. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77931. */
  77932. set: function (value) {
  77933. this.imageProcessingConfiguration.colorCurves = value;
  77934. },
  77935. enumerable: true,
  77936. configurable: true
  77937. });
  77938. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77939. /**
  77940. * Gets wether the color curves effect is enabled.
  77941. */
  77942. get: function () {
  77943. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77944. },
  77945. /**
  77946. * Sets wether the color curves effect is enabled.
  77947. */
  77948. set: function (value) {
  77949. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77950. },
  77951. enumerable: true,
  77952. configurable: true
  77953. });
  77954. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77955. /**
  77956. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77957. */
  77958. get: function () {
  77959. return this.imageProcessingConfiguration.colorGradingTexture;
  77960. },
  77961. /**
  77962. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77963. */
  77964. set: function (value) {
  77965. this.imageProcessingConfiguration.colorGradingTexture = value;
  77966. },
  77967. enumerable: true,
  77968. configurable: true
  77969. });
  77970. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77971. /**
  77972. * Gets wether the color grading effect is enabled.
  77973. */
  77974. get: function () {
  77975. return this.imageProcessingConfiguration.colorGradingEnabled;
  77976. },
  77977. /**
  77978. * Gets wether the color grading effect is enabled.
  77979. */
  77980. set: function (value) {
  77981. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77982. },
  77983. enumerable: true,
  77984. configurable: true
  77985. });
  77986. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77987. /**
  77988. * Gets exposure used in the effect.
  77989. */
  77990. get: function () {
  77991. return this.imageProcessingConfiguration.exposure;
  77992. },
  77993. /**
  77994. * Sets exposure used in the effect.
  77995. */
  77996. set: function (value) {
  77997. this.imageProcessingConfiguration.exposure = value;
  77998. },
  77999. enumerable: true,
  78000. configurable: true
  78001. });
  78002. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78003. /**
  78004. * Gets wether tonemapping is enabled or not.
  78005. */
  78006. get: function () {
  78007. return this._imageProcessingConfiguration.toneMappingEnabled;
  78008. },
  78009. /**
  78010. * Sets wether tonemapping is enabled or not
  78011. */
  78012. set: function (value) {
  78013. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78014. },
  78015. enumerable: true,
  78016. configurable: true
  78017. });
  78018. ;
  78019. ;
  78020. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78021. /**
  78022. * Gets contrast used in the effect.
  78023. */
  78024. get: function () {
  78025. return this.imageProcessingConfiguration.contrast;
  78026. },
  78027. /**
  78028. * Sets contrast used in the effect.
  78029. */
  78030. set: function (value) {
  78031. this.imageProcessingConfiguration.contrast = value;
  78032. },
  78033. enumerable: true,
  78034. configurable: true
  78035. });
  78036. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78037. /**
  78038. * Gets Vignette stretch size.
  78039. */
  78040. get: function () {
  78041. return this.imageProcessingConfiguration.vignetteStretch;
  78042. },
  78043. /**
  78044. * Sets Vignette stretch size.
  78045. */
  78046. set: function (value) {
  78047. this.imageProcessingConfiguration.vignetteStretch = value;
  78048. },
  78049. enumerable: true,
  78050. configurable: true
  78051. });
  78052. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78053. /**
  78054. * Gets Vignette centre X Offset.
  78055. */
  78056. get: function () {
  78057. return this.imageProcessingConfiguration.vignetteCentreX;
  78058. },
  78059. /**
  78060. * Sets Vignette centre X Offset.
  78061. */
  78062. set: function (value) {
  78063. this.imageProcessingConfiguration.vignetteCentreX = value;
  78064. },
  78065. enumerable: true,
  78066. configurable: true
  78067. });
  78068. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78069. /**
  78070. * Gets Vignette centre Y Offset.
  78071. */
  78072. get: function () {
  78073. return this.imageProcessingConfiguration.vignetteCentreY;
  78074. },
  78075. /**
  78076. * Sets Vignette centre Y Offset.
  78077. */
  78078. set: function (value) {
  78079. this.imageProcessingConfiguration.vignetteCentreY = value;
  78080. },
  78081. enumerable: true,
  78082. configurable: true
  78083. });
  78084. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78085. /**
  78086. * Gets Vignette weight or intensity of the vignette effect.
  78087. */
  78088. get: function () {
  78089. return this.imageProcessingConfiguration.vignetteWeight;
  78090. },
  78091. /**
  78092. * Sets Vignette weight or intensity of the vignette effect.
  78093. */
  78094. set: function (value) {
  78095. this.imageProcessingConfiguration.vignetteWeight = value;
  78096. },
  78097. enumerable: true,
  78098. configurable: true
  78099. });
  78100. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78101. /**
  78102. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78103. * if vignetteEnabled is set to true.
  78104. */
  78105. get: function () {
  78106. return this.imageProcessingConfiguration.vignetteColor;
  78107. },
  78108. /**
  78109. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78110. * if vignetteEnabled is set to true.
  78111. */
  78112. set: function (value) {
  78113. this.imageProcessingConfiguration.vignetteColor = value;
  78114. },
  78115. enumerable: true,
  78116. configurable: true
  78117. });
  78118. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78119. /**
  78120. * Gets Camera field of view used by the Vignette effect.
  78121. */
  78122. get: function () {
  78123. return this.imageProcessingConfiguration.vignetteCameraFov;
  78124. },
  78125. /**
  78126. * Sets Camera field of view used by the Vignette effect.
  78127. */
  78128. set: function (value) {
  78129. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78130. },
  78131. enumerable: true,
  78132. configurable: true
  78133. });
  78134. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78135. /**
  78136. * Gets the vignette blend mode allowing different kind of effect.
  78137. */
  78138. get: function () {
  78139. return this.imageProcessingConfiguration.vignetteBlendMode;
  78140. },
  78141. /**
  78142. * Sets the vignette blend mode allowing different kind of effect.
  78143. */
  78144. set: function (value) {
  78145. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78146. },
  78147. enumerable: true,
  78148. configurable: true
  78149. });
  78150. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78151. /**
  78152. * Gets wether the vignette effect is enabled.
  78153. */
  78154. get: function () {
  78155. return this.imageProcessingConfiguration.vignetteEnabled;
  78156. },
  78157. /**
  78158. * Sets wether the vignette effect is enabled.
  78159. */
  78160. set: function (value) {
  78161. this.imageProcessingConfiguration.vignetteEnabled = value;
  78162. },
  78163. enumerable: true,
  78164. configurable: true
  78165. });
  78166. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78167. /**
  78168. * Gets wether the input of the processing is in Gamma or Linear Space.
  78169. */
  78170. get: function () {
  78171. return this._fromLinearSpace;
  78172. },
  78173. /**
  78174. * Sets wether the input of the processing is in Gamma or Linear Space.
  78175. */
  78176. set: function (value) {
  78177. if (this._fromLinearSpace === value) {
  78178. return;
  78179. }
  78180. this._fromLinearSpace = value;
  78181. this._updateParameters();
  78182. },
  78183. enumerable: true,
  78184. configurable: true
  78185. });
  78186. ImageProcessingPostProcess.prototype.getClassName = function () {
  78187. return "ImageProcessingPostProcess";
  78188. };
  78189. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78190. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78191. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78192. var defines = "";
  78193. for (var define in this._defines) {
  78194. if (this._defines[define]) {
  78195. defines += "#define " + define + ";\r\n";
  78196. }
  78197. }
  78198. var samplers = ["textureSampler"];
  78199. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78200. var uniforms = ["scale"];
  78201. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78202. this.updateEffect(defines, uniforms, samplers);
  78203. };
  78204. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78205. _super.prototype.dispose.call(this, camera);
  78206. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78207. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78208. }
  78209. this.imageProcessingConfiguration.applyByPostProcess = false;
  78210. };
  78211. __decorate([
  78212. BABYLON.serialize()
  78213. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78214. return ImageProcessingPostProcess;
  78215. }(BABYLON.PostProcess));
  78216. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78217. })(BABYLON || (BABYLON = {}));
  78218. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78219. var BABYLON;
  78220. (function (BABYLON) {
  78221. /**
  78222. * Class used to store bone information
  78223. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78224. */
  78225. var Bone = /** @class */ (function (_super) {
  78226. __extends(Bone, _super);
  78227. /**
  78228. * Create a new bone
  78229. * @param name defines the bone name
  78230. * @param skeleton defines the parent skeleton
  78231. * @param parentBone defines the parent (can be null if the bone is the root)
  78232. * @param localMatrix defines the local matrix
  78233. * @param restPose defines the rest pose matrix
  78234. * @param baseMatrix defines the base matrix
  78235. * @param index defines index of the bone in the hiearchy
  78236. */
  78237. function Bone(
  78238. /**
  78239. * defines the bone name
  78240. */
  78241. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78242. if (parentBone === void 0) { parentBone = null; }
  78243. if (localMatrix === void 0) { localMatrix = null; }
  78244. if (restPose === void 0) { restPose = null; }
  78245. if (baseMatrix === void 0) { baseMatrix = null; }
  78246. if (index === void 0) { index = null; }
  78247. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78248. _this.name = name;
  78249. /**
  78250. * Gets the list of child bones
  78251. */
  78252. _this.children = new Array();
  78253. /** Gets the animations associated with this bone */
  78254. _this.animations = new Array();
  78255. /**
  78256. * @hidden Internal only
  78257. * Set this value to map this bone to a different index in the transform matrices
  78258. * Set this value to -1 to exclude the bone from the transform matrices
  78259. */
  78260. _this._index = null;
  78261. _this._absoluteTransform = new BABYLON.Matrix();
  78262. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78263. _this._scalingDeterminant = 1;
  78264. _this._worldTransform = new BABYLON.Matrix();
  78265. _this._needToDecompose = true;
  78266. _this._needToCompose = false;
  78267. _this._skeleton = skeleton;
  78268. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78269. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78270. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78271. _this._index = index;
  78272. skeleton.bones.push(_this);
  78273. _this.setParent(parentBone, false);
  78274. if (baseMatrix || localMatrix) {
  78275. _this._updateDifferenceMatrix();
  78276. }
  78277. return _this;
  78278. }
  78279. Object.defineProperty(Bone.prototype, "_matrix", {
  78280. /** @hidden */
  78281. get: function () {
  78282. this._compose();
  78283. return this._localMatrix;
  78284. },
  78285. /** @hidden */
  78286. set: function (value) {
  78287. this._localMatrix.copyFrom(value);
  78288. this._needToDecompose = true;
  78289. },
  78290. enumerable: true,
  78291. configurable: true
  78292. });
  78293. // Members
  78294. /**
  78295. * Gets the parent skeleton
  78296. * @returns a skeleton
  78297. */
  78298. Bone.prototype.getSkeleton = function () {
  78299. return this._skeleton;
  78300. };
  78301. /**
  78302. * Gets parent bone
  78303. * @returns a bone or null if the bone is the root of the bone hierarchy
  78304. */
  78305. Bone.prototype.getParent = function () {
  78306. return this._parent;
  78307. };
  78308. /**
  78309. * Sets the parent bone
  78310. * @param parent defines the parent (can be null if the bone is the root)
  78311. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78312. */
  78313. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78314. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78315. if (this._parent === parent) {
  78316. return;
  78317. }
  78318. if (this._parent) {
  78319. var index = this._parent.children.indexOf(this);
  78320. if (index !== -1) {
  78321. this._parent.children.splice(index, 1);
  78322. }
  78323. }
  78324. this._parent = parent;
  78325. if (this._parent) {
  78326. this._parent.children.push(this);
  78327. }
  78328. if (updateDifferenceMatrix) {
  78329. this._updateDifferenceMatrix();
  78330. }
  78331. this.markAsDirty();
  78332. };
  78333. /**
  78334. * Gets the local matrix
  78335. * @returns a matrix
  78336. */
  78337. Bone.prototype.getLocalMatrix = function () {
  78338. this._compose();
  78339. return this._localMatrix;
  78340. };
  78341. /**
  78342. * Gets the base matrix (initial matrix which remains unchanged)
  78343. * @returns a matrix
  78344. */
  78345. Bone.prototype.getBaseMatrix = function () {
  78346. return this._baseMatrix;
  78347. };
  78348. /**
  78349. * Gets the rest pose matrix
  78350. * @returns a matrix
  78351. */
  78352. Bone.prototype.getRestPose = function () {
  78353. return this._restPose;
  78354. };
  78355. /**
  78356. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78357. */
  78358. Bone.prototype.getWorldMatrix = function () {
  78359. return this._worldTransform;
  78360. };
  78361. /**
  78362. * Sets the local matrix to rest pose matrix
  78363. */
  78364. Bone.prototype.returnToRest = function () {
  78365. this.updateMatrix(this._restPose.clone());
  78366. };
  78367. /**
  78368. * Gets the inverse of the absolute transform matrix.
  78369. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78370. * @returns a matrix
  78371. */
  78372. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78373. return this._invertedAbsoluteTransform;
  78374. };
  78375. /**
  78376. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78377. * @returns a matrix
  78378. */
  78379. Bone.prototype.getAbsoluteTransform = function () {
  78380. return this._absoluteTransform;
  78381. };
  78382. Object.defineProperty(Bone.prototype, "position", {
  78383. // Properties (matches AbstractMesh properties)
  78384. /** Gets or sets current position (in local space) */
  78385. get: function () {
  78386. this._decompose();
  78387. return this._localPosition;
  78388. },
  78389. set: function (newPosition) {
  78390. this._decompose();
  78391. this._localPosition.copyFrom(newPosition);
  78392. this._markAsDirtyAndCompose();
  78393. },
  78394. enumerable: true,
  78395. configurable: true
  78396. });
  78397. Object.defineProperty(Bone.prototype, "rotation", {
  78398. /** Gets or sets current rotation (in local space) */
  78399. get: function () {
  78400. return this.getRotation();
  78401. },
  78402. set: function (newRotation) {
  78403. this.setRotation(newRotation);
  78404. },
  78405. enumerable: true,
  78406. configurable: true
  78407. });
  78408. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78409. /** Gets or sets current rotation quaternion (in local space) */
  78410. get: function () {
  78411. this._decompose();
  78412. return this._localRotation;
  78413. },
  78414. set: function (newRotation) {
  78415. this.setRotationQuaternion(newRotation);
  78416. },
  78417. enumerable: true,
  78418. configurable: true
  78419. });
  78420. Object.defineProperty(Bone.prototype, "scaling", {
  78421. /** Gets or sets current scaling (in local space) */
  78422. get: function () {
  78423. return this.getScale();
  78424. },
  78425. set: function (newScaling) {
  78426. this.setScale(newScaling);
  78427. },
  78428. enumerable: true,
  78429. configurable: true
  78430. });
  78431. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78432. /**
  78433. * Gets the animation properties override
  78434. */
  78435. get: function () {
  78436. return this._skeleton.animationPropertiesOverride;
  78437. },
  78438. enumerable: true,
  78439. configurable: true
  78440. });
  78441. // Methods
  78442. Bone.prototype._decompose = function () {
  78443. if (!this._needToDecompose) {
  78444. return;
  78445. }
  78446. this._needToDecompose = false;
  78447. if (!this._localScaling) {
  78448. this._localScaling = BABYLON.Vector3.Zero();
  78449. this._localRotation = BABYLON.Quaternion.Zero();
  78450. this._localPosition = BABYLON.Vector3.Zero();
  78451. }
  78452. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78453. };
  78454. Bone.prototype._compose = function () {
  78455. if (!this._needToCompose) {
  78456. return;
  78457. }
  78458. this._needToCompose = false;
  78459. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78460. };
  78461. /**
  78462. * Update the base and local matrices
  78463. * @param matrix defines the new base or local matrix
  78464. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78465. * @param updateLocalMatrix defines if the local matrix should be updated
  78466. */
  78467. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78468. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78469. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78470. this._baseMatrix.copyFrom(matrix);
  78471. if (updateDifferenceMatrix) {
  78472. this._updateDifferenceMatrix();
  78473. }
  78474. if (updateLocalMatrix) {
  78475. this._localMatrix.copyFrom(matrix);
  78476. this._markAsDirtyAndDecompose();
  78477. }
  78478. else {
  78479. this.markAsDirty();
  78480. }
  78481. };
  78482. /** @hidden */
  78483. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78484. if (updateChildren === void 0) { updateChildren = true; }
  78485. if (!rootMatrix) {
  78486. rootMatrix = this._baseMatrix;
  78487. }
  78488. if (this._parent) {
  78489. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78490. }
  78491. else {
  78492. this._absoluteTransform.copyFrom(rootMatrix);
  78493. }
  78494. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78495. if (updateChildren) {
  78496. for (var index = 0; index < this.children.length; index++) {
  78497. this.children[index]._updateDifferenceMatrix();
  78498. }
  78499. }
  78500. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78501. };
  78502. /**
  78503. * Flag the bone as dirty (Forcing it to update everything)
  78504. */
  78505. Bone.prototype.markAsDirty = function () {
  78506. this._currentRenderId++;
  78507. this._childRenderId++;
  78508. this._skeleton._markAsDirty();
  78509. };
  78510. Bone.prototype._markAsDirtyAndCompose = function () {
  78511. this.markAsDirty();
  78512. this._needToCompose = true;
  78513. };
  78514. Bone.prototype._markAsDirtyAndDecompose = function () {
  78515. this.markAsDirty();
  78516. this._needToDecompose = true;
  78517. };
  78518. /**
  78519. * Copy an animation range from another bone
  78520. * @param source defines the source bone
  78521. * @param rangeName defines the range name to copy
  78522. * @param frameOffset defines the frame offset
  78523. * @param rescaleAsRequired defines if rescaling must be applied if required
  78524. * @param skelDimensionsRatio defines the scaling ratio
  78525. * @returns true if operation was successful
  78526. */
  78527. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78528. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78529. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78530. // all animation may be coming from a library skeleton, so may need to create animation
  78531. if (this.animations.length === 0) {
  78532. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78533. this.animations[0].setKeys([]);
  78534. }
  78535. // get animation info / verify there is such a range from the source bone
  78536. var sourceRange = source.animations[0].getRange(rangeName);
  78537. if (!sourceRange) {
  78538. return false;
  78539. }
  78540. var from = sourceRange.from;
  78541. var to = sourceRange.to;
  78542. var sourceKeys = source.animations[0].getKeys();
  78543. // rescaling prep
  78544. var sourceBoneLength = source.length;
  78545. var sourceParent = source.getParent();
  78546. var parent = this.getParent();
  78547. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78548. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78549. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78550. var destKeys = this.animations[0].getKeys();
  78551. // loop vars declaration
  78552. var orig;
  78553. var origTranslation;
  78554. var mat;
  78555. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78556. orig = sourceKeys[key];
  78557. if (orig.frame >= from && orig.frame <= to) {
  78558. if (rescaleAsRequired) {
  78559. mat = orig.value.clone();
  78560. // scale based on parent ratio, when bone has parent
  78561. if (parentScalingReqd) {
  78562. origTranslation = mat.getTranslation();
  78563. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78564. // scale based on skeleton dimension ratio when root bone, and value is passed
  78565. }
  78566. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78567. origTranslation = mat.getTranslation();
  78568. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78569. // use original when root bone, and no data for skelDimensionsRatio
  78570. }
  78571. else {
  78572. mat = orig.value;
  78573. }
  78574. }
  78575. else {
  78576. mat = orig.value;
  78577. }
  78578. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78579. }
  78580. }
  78581. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78582. return true;
  78583. };
  78584. /**
  78585. * Translate the bone in local or world space
  78586. * @param vec The amount to translate the bone
  78587. * @param space The space that the translation is in
  78588. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78589. */
  78590. Bone.prototype.translate = function (vec, space, mesh) {
  78591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78592. var lm = this.getLocalMatrix();
  78593. if (space == BABYLON.Space.LOCAL) {
  78594. lm.m[12] += vec.x;
  78595. lm.m[13] += vec.y;
  78596. lm.m[14] += vec.z;
  78597. }
  78598. else {
  78599. var wm = null;
  78600. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78601. if (mesh) {
  78602. wm = mesh.getWorldMatrix();
  78603. }
  78604. this._skeleton.computeAbsoluteTransforms();
  78605. var tmat = Bone._tmpMats[0];
  78606. var tvec = Bone._tmpVecs[0];
  78607. if (this._parent) {
  78608. if (mesh && wm) {
  78609. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78610. tmat.multiplyToRef(wm, tmat);
  78611. }
  78612. else {
  78613. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78614. }
  78615. }
  78616. tmat.m[12] = 0;
  78617. tmat.m[13] = 0;
  78618. tmat.m[14] = 0;
  78619. tmat.invert();
  78620. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78621. lm.m[12] += tvec.x;
  78622. lm.m[13] += tvec.y;
  78623. lm.m[14] += tvec.z;
  78624. }
  78625. this._markAsDirtyAndDecompose();
  78626. };
  78627. /**
  78628. * Set the postion of the bone in local or world space
  78629. * @param position The position to set the bone
  78630. * @param space The space that the position is in
  78631. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78632. */
  78633. Bone.prototype.setPosition = function (position, space, mesh) {
  78634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78635. var lm = this.getLocalMatrix();
  78636. if (space == BABYLON.Space.LOCAL) {
  78637. lm.m[12] = position.x;
  78638. lm.m[13] = position.y;
  78639. lm.m[14] = position.z;
  78640. }
  78641. else {
  78642. var wm = null;
  78643. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78644. if (mesh) {
  78645. wm = mesh.getWorldMatrix();
  78646. }
  78647. this._skeleton.computeAbsoluteTransforms();
  78648. var tmat = Bone._tmpMats[0];
  78649. var vec = Bone._tmpVecs[0];
  78650. if (this._parent) {
  78651. if (mesh && wm) {
  78652. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78653. tmat.multiplyToRef(wm, tmat);
  78654. }
  78655. else {
  78656. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78657. }
  78658. }
  78659. tmat.invert();
  78660. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78661. lm.m[12] = vec.x;
  78662. lm.m[13] = vec.y;
  78663. lm.m[14] = vec.z;
  78664. }
  78665. this._markAsDirtyAndDecompose();
  78666. };
  78667. /**
  78668. * Set the absolute position of the bone (world space)
  78669. * @param position The position to set the bone
  78670. * @param mesh The mesh that this bone is attached to
  78671. */
  78672. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78673. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78674. };
  78675. /**
  78676. * Scale the bone on the x, y and z axes (in local space)
  78677. * @param x The amount to scale the bone on the x axis
  78678. * @param y The amount to scale the bone on the y axis
  78679. * @param z The amount to scale the bone on the z axis
  78680. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78681. */
  78682. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78683. if (scaleChildren === void 0) { scaleChildren = false; }
  78684. var locMat = this.getLocalMatrix();
  78685. // Apply new scaling on top of current local matrix
  78686. var scaleMat = Bone._tmpMats[0];
  78687. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78688. scaleMat.multiplyToRef(locMat, locMat);
  78689. // Invert scaling matrix and apply the inverse to all children
  78690. scaleMat.invert();
  78691. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78692. var child = _a[_i];
  78693. var cm = child.getLocalMatrix();
  78694. cm.multiplyToRef(scaleMat, cm);
  78695. cm.m[12] *= x;
  78696. cm.m[13] *= y;
  78697. cm.m[14] *= z;
  78698. child._markAsDirtyAndDecompose();
  78699. }
  78700. this._markAsDirtyAndDecompose();
  78701. if (scaleChildren) {
  78702. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78703. var child = _c[_b];
  78704. child.scale(x, y, z, scaleChildren);
  78705. }
  78706. }
  78707. };
  78708. /**
  78709. * Set the bone scaling in local space
  78710. * @param scale defines the scaling vector
  78711. */
  78712. Bone.prototype.setScale = function (scale) {
  78713. this._decompose();
  78714. this._localScaling.copyFrom(scale);
  78715. this._markAsDirtyAndCompose();
  78716. };
  78717. /**
  78718. * Gets the current scaling in local space
  78719. * @returns the current scaling vector
  78720. */
  78721. Bone.prototype.getScale = function () {
  78722. this._decompose();
  78723. return this._localScaling;
  78724. };
  78725. /**
  78726. * Gets the current scaling in local space and stores it in a target vector
  78727. * @param result defines the target vector
  78728. */
  78729. Bone.prototype.getScaleToRef = function (result) {
  78730. this._decompose();
  78731. result.copyFrom(this._localScaling);
  78732. };
  78733. /**
  78734. * Set the yaw, pitch, and roll of the bone in local or world space
  78735. * @param yaw The rotation of the bone on the y axis
  78736. * @param pitch The rotation of the bone on the x axis
  78737. * @param roll The rotation of the bone on the z axis
  78738. * @param space The space that the axes of rotation are in
  78739. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78740. */
  78741. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78742. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78743. if (space === BABYLON.Space.LOCAL) {
  78744. var quat = Bone._tmpQuat;
  78745. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78746. this.setRotationQuaternion(quat, space, mesh);
  78747. return;
  78748. }
  78749. var rotMatInv = Bone._tmpMats[0];
  78750. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78751. return;
  78752. }
  78753. var rotMat = Bone._tmpMats[1];
  78754. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78755. rotMatInv.multiplyToRef(rotMat, rotMat);
  78756. this._rotateWithMatrix(rotMat, space, mesh);
  78757. };
  78758. /**
  78759. * Add a rotation to the bone on an axis in local or world space
  78760. * @param axis The axis to rotate the bone on
  78761. * @param amount The amount to rotate the bone
  78762. * @param space The space that the axis is in
  78763. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78764. */
  78765. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78766. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78767. var rmat = Bone._tmpMats[0];
  78768. rmat.m[12] = 0;
  78769. rmat.m[13] = 0;
  78770. rmat.m[14] = 0;
  78771. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78772. this._rotateWithMatrix(rmat, space, mesh);
  78773. };
  78774. /**
  78775. * Set the rotation of the bone to a particular axis angle in local or world space
  78776. * @param axis The axis to rotate the bone on
  78777. * @param angle The angle that the bone should be rotated to
  78778. * @param space The space that the axis is in
  78779. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78780. */
  78781. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78782. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78783. if (space === BABYLON.Space.LOCAL) {
  78784. var quat = Bone._tmpQuat;
  78785. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78786. this.setRotationQuaternion(quat, space, mesh);
  78787. return;
  78788. }
  78789. var rotMatInv = Bone._tmpMats[0];
  78790. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78791. return;
  78792. }
  78793. var rotMat = Bone._tmpMats[1];
  78794. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78795. rotMatInv.multiplyToRef(rotMat, rotMat);
  78796. this._rotateWithMatrix(rotMat, space, mesh);
  78797. };
  78798. /**
  78799. * Set the euler rotation of the bone in local of world space
  78800. * @param rotation The euler rotation that the bone should be set to
  78801. * @param space The space that the rotation is in
  78802. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78803. */
  78804. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78805. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78806. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78807. };
  78808. /**
  78809. * Set the quaternion rotation of the bone in local of world space
  78810. * @param quat The quaternion rotation that the bone should be set to
  78811. * @param space The space that the rotation is in
  78812. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78813. */
  78814. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78815. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78816. if (space === BABYLON.Space.LOCAL) {
  78817. this._decompose();
  78818. this._localRotation.copyFrom(quat);
  78819. this._markAsDirtyAndCompose();
  78820. return;
  78821. }
  78822. var rotMatInv = Bone._tmpMats[0];
  78823. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78824. return;
  78825. }
  78826. var rotMat = Bone._tmpMats[1];
  78827. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78828. rotMatInv.multiplyToRef(rotMat, rotMat);
  78829. this._rotateWithMatrix(rotMat, space, mesh);
  78830. };
  78831. /**
  78832. * Set the rotation matrix of the bone in local of world space
  78833. * @param rotMat The rotation matrix that the bone should be set to
  78834. * @param space The space that the rotation is in
  78835. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78836. */
  78837. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78838. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78839. if (space === BABYLON.Space.LOCAL) {
  78840. var quat = Bone._tmpQuat;
  78841. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78842. this.setRotationQuaternion(quat, space, mesh);
  78843. return;
  78844. }
  78845. var rotMatInv = Bone._tmpMats[0];
  78846. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78847. return;
  78848. }
  78849. var rotMat2 = Bone._tmpMats[1];
  78850. rotMat2.copyFrom(rotMat);
  78851. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78852. this._rotateWithMatrix(rotMat2, space, mesh);
  78853. };
  78854. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78855. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78856. var lmat = this.getLocalMatrix();
  78857. var lx = lmat.m[12];
  78858. var ly = lmat.m[13];
  78859. var lz = lmat.m[14];
  78860. var parent = this.getParent();
  78861. var parentScale = Bone._tmpMats[3];
  78862. var parentScaleInv = Bone._tmpMats[4];
  78863. if (parent && space == BABYLON.Space.WORLD) {
  78864. if (mesh) {
  78865. parentScale.copyFrom(mesh.getWorldMatrix());
  78866. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78867. }
  78868. else {
  78869. parentScale.copyFrom(parent.getAbsoluteTransform());
  78870. }
  78871. parentScaleInv.copyFrom(parentScale);
  78872. parentScaleInv.invert();
  78873. lmat.multiplyToRef(parentScale, lmat);
  78874. lmat.multiplyToRef(rmat, lmat);
  78875. lmat.multiplyToRef(parentScaleInv, lmat);
  78876. }
  78877. else {
  78878. if (space == BABYLON.Space.WORLD && mesh) {
  78879. parentScale.copyFrom(mesh.getWorldMatrix());
  78880. parentScaleInv.copyFrom(parentScale);
  78881. parentScaleInv.invert();
  78882. lmat.multiplyToRef(parentScale, lmat);
  78883. lmat.multiplyToRef(rmat, lmat);
  78884. lmat.multiplyToRef(parentScaleInv, lmat);
  78885. }
  78886. else {
  78887. lmat.multiplyToRef(rmat, lmat);
  78888. }
  78889. }
  78890. lmat.m[12] = lx;
  78891. lmat.m[13] = ly;
  78892. lmat.m[14] = lz;
  78893. this.computeAbsoluteTransforms();
  78894. this._markAsDirtyAndDecompose();
  78895. };
  78896. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78897. var scaleMatrix = Bone._tmpMats[2];
  78898. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78899. if (mesh) {
  78900. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78901. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78902. }
  78903. rotMatInv.invert();
  78904. if (isNaN(rotMatInv.m[0])) {
  78905. // Matrix failed to invert.
  78906. // This can happen if scale is zero for example.
  78907. return false;
  78908. }
  78909. scaleMatrix.m[0] *= this._scalingDeterminant;
  78910. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78911. return true;
  78912. };
  78913. /**
  78914. * Get the position of the bone in local or world space
  78915. * @param space The space that the returned position is in
  78916. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78917. * @returns The position of the bone
  78918. */
  78919. Bone.prototype.getPosition = function (space, mesh) {
  78920. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78921. if (mesh === void 0) { mesh = null; }
  78922. var pos = BABYLON.Vector3.Zero();
  78923. this.getPositionToRef(space, mesh, pos);
  78924. return pos;
  78925. };
  78926. /**
  78927. * Copy the position of the bone to a vector3 in local or world space
  78928. * @param space The space that the returned position is in
  78929. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78930. * @param result The vector3 to copy the position to
  78931. */
  78932. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78934. if (space == BABYLON.Space.LOCAL) {
  78935. var lm = this.getLocalMatrix();
  78936. result.x = lm.m[12];
  78937. result.y = lm.m[13];
  78938. result.z = lm.m[14];
  78939. }
  78940. else {
  78941. var wm = null;
  78942. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78943. if (mesh) {
  78944. wm = mesh.getWorldMatrix();
  78945. }
  78946. this._skeleton.computeAbsoluteTransforms();
  78947. var tmat = Bone._tmpMats[0];
  78948. if (mesh && wm) {
  78949. tmat.copyFrom(this.getAbsoluteTransform());
  78950. tmat.multiplyToRef(wm, tmat);
  78951. }
  78952. else {
  78953. tmat = this.getAbsoluteTransform();
  78954. }
  78955. result.x = tmat.m[12];
  78956. result.y = tmat.m[13];
  78957. result.z = tmat.m[14];
  78958. }
  78959. };
  78960. /**
  78961. * Get the absolute position of the bone (world space)
  78962. * @param mesh The mesh that this bone is attached to
  78963. * @returns The absolute position of the bone
  78964. */
  78965. Bone.prototype.getAbsolutePosition = function (mesh) {
  78966. if (mesh === void 0) { mesh = null; }
  78967. var pos = BABYLON.Vector3.Zero();
  78968. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78969. return pos;
  78970. };
  78971. /**
  78972. * Copy the absolute position of the bone (world space) to the result param
  78973. * @param mesh The mesh that this bone is attached to
  78974. * @param result The vector3 to copy the absolute position to
  78975. */
  78976. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78977. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78978. };
  78979. /**
  78980. * Compute the absolute transforms of this bone and its children
  78981. */
  78982. Bone.prototype.computeAbsoluteTransforms = function () {
  78983. this._compose();
  78984. if (this._parent) {
  78985. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78986. }
  78987. else {
  78988. this._absoluteTransform.copyFrom(this._localMatrix);
  78989. var poseMatrix = this._skeleton.getPoseMatrix();
  78990. if (poseMatrix) {
  78991. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78992. }
  78993. }
  78994. var children = this.children;
  78995. var len = children.length;
  78996. for (var i = 0; i < len; i++) {
  78997. children[i].computeAbsoluteTransforms();
  78998. }
  78999. };
  79000. /**
  79001. * Get the world direction from an axis that is in the local space of the bone
  79002. * @param localAxis The local direction that is used to compute the world direction
  79003. * @param mesh The mesh that this bone is attached to
  79004. * @returns The world direction
  79005. */
  79006. Bone.prototype.getDirection = function (localAxis, mesh) {
  79007. if (mesh === void 0) { mesh = null; }
  79008. var result = BABYLON.Vector3.Zero();
  79009. this.getDirectionToRef(localAxis, mesh, result);
  79010. return result;
  79011. };
  79012. /**
  79013. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79014. * @param localAxis The local direction that is used to compute the world direction
  79015. * @param mesh The mesh that this bone is attached to
  79016. * @param result The vector3 that the world direction will be copied to
  79017. */
  79018. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79019. if (mesh === void 0) { mesh = null; }
  79020. var wm = null;
  79021. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79022. if (mesh) {
  79023. wm = mesh.getWorldMatrix();
  79024. }
  79025. this._skeleton.computeAbsoluteTransforms();
  79026. var mat = Bone._tmpMats[0];
  79027. mat.copyFrom(this.getAbsoluteTransform());
  79028. if (mesh && wm) {
  79029. mat.multiplyToRef(wm, mat);
  79030. }
  79031. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79032. result.normalize();
  79033. };
  79034. /**
  79035. * Get the euler rotation of the bone in local or world space
  79036. * @param space The space that the rotation should be in
  79037. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79038. * @returns The euler rotation
  79039. */
  79040. Bone.prototype.getRotation = function (space, mesh) {
  79041. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79042. if (mesh === void 0) { mesh = null; }
  79043. var result = BABYLON.Vector3.Zero();
  79044. this.getRotationToRef(space, mesh, result);
  79045. return result;
  79046. };
  79047. /**
  79048. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79049. * @param space The space that the rotation should be in
  79050. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79051. * @param result The vector3 that the rotation should be copied to
  79052. */
  79053. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79054. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79055. if (mesh === void 0) { mesh = null; }
  79056. var quat = Bone._tmpQuat;
  79057. this.getRotationQuaternionToRef(space, mesh, quat);
  79058. quat.toEulerAnglesToRef(result);
  79059. };
  79060. /**
  79061. * Get the quaternion rotation of the bone in either local or world space
  79062. * @param space The space that the rotation should be in
  79063. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79064. * @returns The quaternion rotation
  79065. */
  79066. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79067. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79068. if (mesh === void 0) { mesh = null; }
  79069. var result = BABYLON.Quaternion.Identity();
  79070. this.getRotationQuaternionToRef(space, mesh, result);
  79071. return result;
  79072. };
  79073. /**
  79074. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79075. * @param space The space that the rotation should be in
  79076. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79077. * @param result The quaternion that the rotation should be copied to
  79078. */
  79079. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79080. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79081. if (mesh === void 0) { mesh = null; }
  79082. if (space == BABYLON.Space.LOCAL) {
  79083. this._decompose();
  79084. result.copyFrom(this._localRotation);
  79085. }
  79086. else {
  79087. var mat = Bone._tmpMats[0];
  79088. var amat = this.getAbsoluteTransform();
  79089. if (mesh) {
  79090. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79091. }
  79092. else {
  79093. mat.copyFrom(amat);
  79094. }
  79095. mat.m[0] *= this._scalingDeterminant;
  79096. mat.m[1] *= this._scalingDeterminant;
  79097. mat.m[2] *= this._scalingDeterminant;
  79098. mat.decompose(undefined, result, undefined);
  79099. }
  79100. };
  79101. /**
  79102. * Get the rotation matrix of the bone in local or world space
  79103. * @param space The space that the rotation should be in
  79104. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79105. * @returns The rotation matrix
  79106. */
  79107. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79108. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79109. var result = BABYLON.Matrix.Identity();
  79110. this.getRotationMatrixToRef(space, mesh, result);
  79111. return result;
  79112. };
  79113. /**
  79114. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79115. * @param space The space that the rotation should be in
  79116. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79117. * @param result The quaternion that the rotation should be copied to
  79118. */
  79119. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79120. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79121. if (space == BABYLON.Space.LOCAL) {
  79122. this.getLocalMatrix().getRotationMatrixToRef(result);
  79123. }
  79124. else {
  79125. var mat = Bone._tmpMats[0];
  79126. var amat = this.getAbsoluteTransform();
  79127. if (mesh) {
  79128. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79129. }
  79130. else {
  79131. mat.copyFrom(amat);
  79132. }
  79133. mat.m[0] *= this._scalingDeterminant;
  79134. mat.m[1] *= this._scalingDeterminant;
  79135. mat.m[2] *= this._scalingDeterminant;
  79136. mat.getRotationMatrixToRef(result);
  79137. }
  79138. };
  79139. /**
  79140. * Get the world position of a point that is in the local space of the bone
  79141. * @param position The local position
  79142. * @param mesh The mesh that this bone is attached to
  79143. * @returns The world position
  79144. */
  79145. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79146. if (mesh === void 0) { mesh = null; }
  79147. var result = BABYLON.Vector3.Zero();
  79148. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79149. return result;
  79150. };
  79151. /**
  79152. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79153. * @param position The local position
  79154. * @param mesh The mesh that this bone is attached to
  79155. * @param result The vector3 that the world position should be copied to
  79156. */
  79157. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79158. if (mesh === void 0) { mesh = null; }
  79159. var wm = null;
  79160. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79161. if (mesh) {
  79162. wm = mesh.getWorldMatrix();
  79163. }
  79164. this._skeleton.computeAbsoluteTransforms();
  79165. var tmat = Bone._tmpMats[0];
  79166. if (mesh && wm) {
  79167. tmat.copyFrom(this.getAbsoluteTransform());
  79168. tmat.multiplyToRef(wm, tmat);
  79169. }
  79170. else {
  79171. tmat = this.getAbsoluteTransform();
  79172. }
  79173. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79174. };
  79175. /**
  79176. * Get the local position of a point that is in world space
  79177. * @param position The world position
  79178. * @param mesh The mesh that this bone is attached to
  79179. * @returns The local position
  79180. */
  79181. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79182. if (mesh === void 0) { mesh = null; }
  79183. var result = BABYLON.Vector3.Zero();
  79184. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79185. return result;
  79186. };
  79187. /**
  79188. * Get the local position of a point that is in world space and copy it to the result param
  79189. * @param position The world position
  79190. * @param mesh The mesh that this bone is attached to
  79191. * @param result The vector3 that the local position should be copied to
  79192. */
  79193. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79194. if (mesh === void 0) { mesh = null; }
  79195. var wm = null;
  79196. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79197. if (mesh) {
  79198. wm = mesh.getWorldMatrix();
  79199. }
  79200. this._skeleton.computeAbsoluteTransforms();
  79201. var tmat = Bone._tmpMats[0];
  79202. tmat.copyFrom(this.getAbsoluteTransform());
  79203. if (mesh && wm) {
  79204. tmat.multiplyToRef(wm, tmat);
  79205. }
  79206. tmat.invert();
  79207. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79208. };
  79209. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79210. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79211. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79212. return Bone;
  79213. }(BABYLON.Node));
  79214. BABYLON.Bone = Bone;
  79215. })(BABYLON || (BABYLON = {}));
  79216. //# sourceMappingURL=babylon.bone.js.map
  79217. var BABYLON;
  79218. (function (BABYLON) {
  79219. /**
  79220. * Class used to apply inverse kinematics to bones
  79221. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79222. */
  79223. var BoneIKController = /** @class */ (function () {
  79224. /**
  79225. * Creates a new BoneIKController
  79226. * @param mesh defines the mesh to control
  79227. * @param bone defines the bone to control
  79228. * @param options defines options to set up the controller
  79229. */
  79230. function BoneIKController(mesh, bone, options) {
  79231. /**
  79232. * Gets or sets the target position
  79233. */
  79234. this.targetPosition = BABYLON.Vector3.Zero();
  79235. /**
  79236. * Gets or sets the pole target position
  79237. */
  79238. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79239. /**
  79240. * Gets or sets the pole target local offset
  79241. */
  79242. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79243. /**
  79244. * Gets or sets the pole angle
  79245. */
  79246. this.poleAngle = 0;
  79247. /**
  79248. * 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)
  79249. */
  79250. this.slerpAmount = 1;
  79251. this._bone1Quat = BABYLON.Quaternion.Identity();
  79252. this._bone1Mat = BABYLON.Matrix.Identity();
  79253. this._bone2Ang = Math.PI;
  79254. this._maxAngle = Math.PI;
  79255. this._rightHandedSystem = false;
  79256. this._bendAxis = BABYLON.Vector3.Right();
  79257. this._slerping = false;
  79258. this._adjustRoll = 0;
  79259. this._bone2 = bone;
  79260. this._bone1 = bone.getParent();
  79261. if (!this._bone1) {
  79262. return;
  79263. }
  79264. this.mesh = mesh;
  79265. var bonePos = bone.getPosition();
  79266. if (bone.getAbsoluteTransform().determinant() > 0) {
  79267. this._rightHandedSystem = true;
  79268. this._bendAxis.x = 0;
  79269. this._bendAxis.y = 0;
  79270. this._bendAxis.z = -1;
  79271. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79272. this._adjustRoll = Math.PI * .5;
  79273. this._bendAxis.z = 1;
  79274. }
  79275. }
  79276. if (this._bone1.length) {
  79277. var boneScale1 = this._bone1.getScale();
  79278. var boneScale2 = this._bone2.getScale();
  79279. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79280. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79281. }
  79282. else if (this._bone1.children[0]) {
  79283. mesh.computeWorldMatrix(true);
  79284. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79285. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79286. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79287. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79288. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79289. }
  79290. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79291. this.maxAngle = Math.PI;
  79292. if (options) {
  79293. if (options.targetMesh) {
  79294. this.targetMesh = options.targetMesh;
  79295. this.targetMesh.computeWorldMatrix(true);
  79296. }
  79297. if (options.poleTargetMesh) {
  79298. this.poleTargetMesh = options.poleTargetMesh;
  79299. this.poleTargetMesh.computeWorldMatrix(true);
  79300. }
  79301. else if (options.poleTargetBone) {
  79302. this.poleTargetBone = options.poleTargetBone;
  79303. }
  79304. else if (this._bone1.getParent()) {
  79305. this.poleTargetBone = this._bone1.getParent();
  79306. }
  79307. if (options.poleTargetLocalOffset) {
  79308. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79309. }
  79310. if (options.poleAngle) {
  79311. this.poleAngle = options.poleAngle;
  79312. }
  79313. if (options.bendAxis) {
  79314. this._bendAxis.copyFrom(options.bendAxis);
  79315. }
  79316. if (options.maxAngle) {
  79317. this.maxAngle = options.maxAngle;
  79318. }
  79319. if (options.slerpAmount) {
  79320. this.slerpAmount = options.slerpAmount;
  79321. }
  79322. }
  79323. }
  79324. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79325. /**
  79326. * Gets or sets maximum allowed angle
  79327. */
  79328. get: function () {
  79329. return this._maxAngle;
  79330. },
  79331. set: function (value) {
  79332. this._setMaxAngle(value);
  79333. },
  79334. enumerable: true,
  79335. configurable: true
  79336. });
  79337. BoneIKController.prototype._setMaxAngle = function (ang) {
  79338. if (ang < 0) {
  79339. ang = 0;
  79340. }
  79341. if (ang > Math.PI || ang == undefined) {
  79342. ang = Math.PI;
  79343. }
  79344. this._maxAngle = ang;
  79345. var a = this._bone1Length;
  79346. var b = this._bone2Length;
  79347. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79348. };
  79349. /**
  79350. * Force the controller to update the bones
  79351. */
  79352. BoneIKController.prototype.update = function () {
  79353. var bone1 = this._bone1;
  79354. if (!bone1) {
  79355. return;
  79356. }
  79357. var target = this.targetPosition;
  79358. var poleTarget = this.poleTargetPosition;
  79359. var mat1 = BoneIKController._tmpMats[0];
  79360. var mat2 = BoneIKController._tmpMats[1];
  79361. if (this.targetMesh) {
  79362. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79363. }
  79364. if (this.poleTargetBone) {
  79365. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79366. }
  79367. else if (this.poleTargetMesh) {
  79368. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79369. }
  79370. var bonePos = BoneIKController._tmpVecs[0];
  79371. var zaxis = BoneIKController._tmpVecs[1];
  79372. var xaxis = BoneIKController._tmpVecs[2];
  79373. var yaxis = BoneIKController._tmpVecs[3];
  79374. var upAxis = BoneIKController._tmpVecs[4];
  79375. var _tmpQuat = BoneIKController._tmpQuat;
  79376. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79377. poleTarget.subtractToRef(bonePos, upAxis);
  79378. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79379. upAxis.y = 1;
  79380. }
  79381. else {
  79382. upAxis.normalize();
  79383. }
  79384. target.subtractToRef(bonePos, yaxis);
  79385. yaxis.normalize();
  79386. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79387. zaxis.normalize();
  79388. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79389. xaxis.normalize();
  79390. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79391. var a = this._bone1Length;
  79392. var b = this._bone2Length;
  79393. var c = BABYLON.Vector3.Distance(bonePos, target);
  79394. if (this._maxReach > 0) {
  79395. c = Math.min(this._maxReach, c);
  79396. }
  79397. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79398. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79399. if (acosa > 1) {
  79400. acosa = 1;
  79401. }
  79402. if (acosb > 1) {
  79403. acosb = 1;
  79404. }
  79405. if (acosa < -1) {
  79406. acosa = -1;
  79407. }
  79408. if (acosb < -1) {
  79409. acosb = -1;
  79410. }
  79411. var angA = Math.acos(acosa);
  79412. var angB = Math.acos(acosb);
  79413. var angC = -angA - angB;
  79414. if (this._rightHandedSystem) {
  79415. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79416. mat2.multiplyToRef(mat1, mat1);
  79417. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79418. mat2.multiplyToRef(mat1, mat1);
  79419. }
  79420. else {
  79421. var _tmpVec = BoneIKController._tmpVecs[5];
  79422. _tmpVec.copyFrom(this._bendAxis);
  79423. _tmpVec.x *= -1;
  79424. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79425. mat2.multiplyToRef(mat1, mat1);
  79426. }
  79427. if (this.poleAngle) {
  79428. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79429. mat1.multiplyToRef(mat2, mat1);
  79430. }
  79431. if (this._bone1) {
  79432. if (this.slerpAmount < 1) {
  79433. if (!this._slerping) {
  79434. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79435. }
  79436. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79437. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79438. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79439. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79440. this._slerping = true;
  79441. }
  79442. else {
  79443. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79444. this._bone1Mat.copyFrom(mat1);
  79445. this._slerping = false;
  79446. }
  79447. }
  79448. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79449. this._bone2Ang = angC;
  79450. };
  79451. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79452. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79453. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79454. return BoneIKController;
  79455. }());
  79456. BABYLON.BoneIKController = BoneIKController;
  79457. })(BABYLON || (BABYLON = {}));
  79458. //# sourceMappingURL=babylon.boneIKController.js.map
  79459. var BABYLON;
  79460. (function (BABYLON) {
  79461. /**
  79462. * Class used to make a bone look toward a point in space
  79463. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79464. */
  79465. var BoneLookController = /** @class */ (function () {
  79466. /**
  79467. * Create a BoneLookController
  79468. * @param mesh the mesh that the bone belongs to
  79469. * @param bone the bone that will be looking to the target
  79470. * @param target the target Vector3 to look at
  79471. * @param settings optional settings:
  79472. * * maxYaw: the maximum angle the bone will yaw to
  79473. * * minYaw: the minimum angle the bone will yaw to
  79474. * * maxPitch: the maximum angle the bone will pitch to
  79475. * * minPitch: the minimum angle the bone will yaw to
  79476. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79477. * * upAxis: the up axis of the coordinate system
  79478. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79479. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79480. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79481. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79482. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79483. * * adjustRoll: used to make an adjustment to the roll of the bone
  79484. **/
  79485. function BoneLookController(mesh, bone, target, options) {
  79486. /**
  79487. * The up axis of the coordinate system that is used when the bone is rotated
  79488. */
  79489. this.upAxis = BABYLON.Vector3.Up();
  79490. /**
  79491. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79492. */
  79493. this.upAxisSpace = BABYLON.Space.LOCAL;
  79494. /**
  79495. * Used to make an adjustment to the yaw of the bone
  79496. */
  79497. this.adjustYaw = 0;
  79498. /**
  79499. * Used to make an adjustment to the pitch of the bone
  79500. */
  79501. this.adjustPitch = 0;
  79502. /**
  79503. * Used to make an adjustment to the roll of the bone
  79504. */
  79505. this.adjustRoll = 0;
  79506. /**
  79507. * 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)
  79508. */
  79509. this.slerpAmount = 1;
  79510. this._boneQuat = BABYLON.Quaternion.Identity();
  79511. this._slerping = false;
  79512. this._firstFrameSkipped = false;
  79513. this._fowardAxis = BABYLON.Vector3.Forward();
  79514. this.mesh = mesh;
  79515. this.bone = bone;
  79516. this.target = target;
  79517. if (options) {
  79518. if (options.adjustYaw) {
  79519. this.adjustYaw = options.adjustYaw;
  79520. }
  79521. if (options.adjustPitch) {
  79522. this.adjustPitch = options.adjustPitch;
  79523. }
  79524. if (options.adjustRoll) {
  79525. this.adjustRoll = options.adjustRoll;
  79526. }
  79527. if (options.maxYaw != null) {
  79528. this.maxYaw = options.maxYaw;
  79529. }
  79530. else {
  79531. this.maxYaw = Math.PI;
  79532. }
  79533. if (options.minYaw != null) {
  79534. this.minYaw = options.minYaw;
  79535. }
  79536. else {
  79537. this.minYaw = -Math.PI;
  79538. }
  79539. if (options.maxPitch != null) {
  79540. this.maxPitch = options.maxPitch;
  79541. }
  79542. else {
  79543. this.maxPitch = Math.PI;
  79544. }
  79545. if (options.minPitch != null) {
  79546. this.minPitch = options.minPitch;
  79547. }
  79548. else {
  79549. this.minPitch = -Math.PI;
  79550. }
  79551. if (options.slerpAmount != null) {
  79552. this.slerpAmount = options.slerpAmount;
  79553. }
  79554. if (options.upAxis != null) {
  79555. this.upAxis = options.upAxis;
  79556. }
  79557. if (options.upAxisSpace != null) {
  79558. this.upAxisSpace = options.upAxisSpace;
  79559. }
  79560. if (options.yawAxis != null || options.pitchAxis != null) {
  79561. var newYawAxis = BABYLON.Axis.Y;
  79562. var newPitchAxis = BABYLON.Axis.X;
  79563. if (options.yawAxis != null) {
  79564. newYawAxis = options.yawAxis.clone();
  79565. newYawAxis.normalize();
  79566. }
  79567. if (options.pitchAxis != null) {
  79568. newPitchAxis = options.pitchAxis.clone();
  79569. newPitchAxis.normalize();
  79570. }
  79571. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79572. this._transformYawPitch = BABYLON.Matrix.Identity();
  79573. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79574. this._transformYawPitchInv = this._transformYawPitch.clone();
  79575. this._transformYawPitch.invert();
  79576. }
  79577. }
  79578. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79579. this.upAxisSpace = BABYLON.Space.LOCAL;
  79580. }
  79581. }
  79582. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79583. /**
  79584. * Gets or sets the minimum yaw angle that the bone can look to
  79585. */
  79586. get: function () {
  79587. return this._minYaw;
  79588. },
  79589. set: function (value) {
  79590. this._minYaw = value;
  79591. this._minYawSin = Math.sin(value);
  79592. this._minYawCos = Math.cos(value);
  79593. if (this._maxYaw != null) {
  79594. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79595. this._yawRange = this._maxYaw - this._minYaw;
  79596. }
  79597. },
  79598. enumerable: true,
  79599. configurable: true
  79600. });
  79601. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79602. /**
  79603. * Gets or sets the maximum yaw angle that the bone can look to
  79604. */
  79605. get: function () {
  79606. return this._maxYaw;
  79607. },
  79608. set: function (value) {
  79609. this._maxYaw = value;
  79610. this._maxYawSin = Math.sin(value);
  79611. this._maxYawCos = Math.cos(value);
  79612. if (this._minYaw != null) {
  79613. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79614. this._yawRange = this._maxYaw - this._minYaw;
  79615. }
  79616. },
  79617. enumerable: true,
  79618. configurable: true
  79619. });
  79620. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79621. /**
  79622. * Gets or sets the minimum pitch angle that the bone can look to
  79623. */
  79624. get: function () {
  79625. return this._minPitch;
  79626. },
  79627. set: function (value) {
  79628. this._minPitch = value;
  79629. this._minPitchTan = Math.tan(value);
  79630. },
  79631. enumerable: true,
  79632. configurable: true
  79633. });
  79634. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79635. /**
  79636. * Gets or sets the maximum pitch angle that the bone can look to
  79637. */
  79638. get: function () {
  79639. return this._maxPitch;
  79640. },
  79641. set: function (value) {
  79642. this._maxPitch = value;
  79643. this._maxPitchTan = Math.tan(value);
  79644. },
  79645. enumerable: true,
  79646. configurable: true
  79647. });
  79648. /**
  79649. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79650. */
  79651. BoneLookController.prototype.update = function () {
  79652. //skip the first frame when slerping so that the mesh rotation is correct
  79653. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79654. this._firstFrameSkipped = true;
  79655. return;
  79656. }
  79657. var bone = this.bone;
  79658. var bonePos = BoneLookController._tmpVecs[0];
  79659. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79660. var target = this.target;
  79661. var _tmpMat1 = BoneLookController._tmpMats[0];
  79662. var _tmpMat2 = BoneLookController._tmpMats[1];
  79663. var mesh = this.mesh;
  79664. var parentBone = bone.getParent();
  79665. var upAxis = BoneLookController._tmpVecs[1];
  79666. upAxis.copyFrom(this.upAxis);
  79667. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79668. if (this._transformYawPitch) {
  79669. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79670. }
  79671. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79672. }
  79673. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79674. mesh.getDirectionToRef(upAxis, upAxis);
  79675. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79676. upAxis.normalize();
  79677. }
  79678. }
  79679. var checkYaw = false;
  79680. var checkPitch = false;
  79681. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79682. checkYaw = true;
  79683. }
  79684. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79685. checkPitch = true;
  79686. }
  79687. if (checkYaw || checkPitch) {
  79688. var spaceMat = BoneLookController._tmpMats[2];
  79689. var spaceMatInv = BoneLookController._tmpMats[3];
  79690. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79691. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79692. }
  79693. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79694. spaceMat.copyFrom(mesh.getWorldMatrix());
  79695. }
  79696. else {
  79697. var forwardAxis = BoneLookController._tmpVecs[2];
  79698. forwardAxis.copyFrom(this._fowardAxis);
  79699. if (this._transformYawPitch) {
  79700. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79701. }
  79702. if (parentBone) {
  79703. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79704. }
  79705. else {
  79706. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79707. }
  79708. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79709. rightAxis.normalize();
  79710. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79711. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79712. }
  79713. spaceMat.invertToRef(spaceMatInv);
  79714. var xzlen = null;
  79715. if (checkPitch) {
  79716. var localTarget = BoneLookController._tmpVecs[3];
  79717. target.subtractToRef(bonePos, localTarget);
  79718. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79719. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79720. var pitch = Math.atan2(localTarget.y, xzlen);
  79721. var newPitch = pitch;
  79722. if (pitch > this._maxPitch) {
  79723. localTarget.y = this._maxPitchTan * xzlen;
  79724. newPitch = this._maxPitch;
  79725. }
  79726. else if (pitch < this._minPitch) {
  79727. localTarget.y = this._minPitchTan * xzlen;
  79728. newPitch = this._minPitch;
  79729. }
  79730. if (pitch != newPitch) {
  79731. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79732. localTarget.addInPlace(bonePos);
  79733. target = localTarget;
  79734. }
  79735. }
  79736. if (checkYaw) {
  79737. var localTarget = BoneLookController._tmpVecs[4];
  79738. target.subtractToRef(bonePos, localTarget);
  79739. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79740. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79741. var newYaw = yaw;
  79742. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79743. if (xzlen == null) {
  79744. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79745. }
  79746. if (this._yawRange > Math.PI) {
  79747. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79748. localTarget.z = this._maxYawCos * xzlen;
  79749. localTarget.x = this._maxYawSin * xzlen;
  79750. newYaw = this._maxYaw;
  79751. }
  79752. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79753. localTarget.z = this._minYawCos * xzlen;
  79754. localTarget.x = this._minYawSin * xzlen;
  79755. newYaw = this._minYaw;
  79756. }
  79757. }
  79758. else {
  79759. if (yaw > this._maxYaw) {
  79760. localTarget.z = this._maxYawCos * xzlen;
  79761. localTarget.x = this._maxYawSin * xzlen;
  79762. newYaw = this._maxYaw;
  79763. }
  79764. else if (yaw < this._minYaw) {
  79765. localTarget.z = this._minYawCos * xzlen;
  79766. localTarget.x = this._minYawSin * xzlen;
  79767. newYaw = this._minYaw;
  79768. }
  79769. }
  79770. }
  79771. if (this._slerping && this._yawRange > Math.PI) {
  79772. //are we going to be crossing into the min/max region?
  79773. var boneFwd = BoneLookController._tmpVecs[8];
  79774. boneFwd.copyFrom(BABYLON.Axis.Z);
  79775. if (this._transformYawPitch) {
  79776. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79777. }
  79778. var boneRotMat = BoneLookController._tmpMats[4];
  79779. this._boneQuat.toRotationMatrix(boneRotMat);
  79780. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79781. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79782. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79783. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79784. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79785. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79786. if (angBtwTar > angBtwMidYaw) {
  79787. if (xzlen == null) {
  79788. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79789. }
  79790. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79791. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79792. if (angBtwMin < angBtwMax) {
  79793. newYaw = boneYaw + Math.PI * .75;
  79794. localTarget.z = Math.cos(newYaw) * xzlen;
  79795. localTarget.x = Math.sin(newYaw) * xzlen;
  79796. }
  79797. else {
  79798. newYaw = boneYaw - Math.PI * .75;
  79799. localTarget.z = Math.cos(newYaw) * xzlen;
  79800. localTarget.x = Math.sin(newYaw) * xzlen;
  79801. }
  79802. }
  79803. }
  79804. if (yaw != newYaw) {
  79805. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79806. localTarget.addInPlace(bonePos);
  79807. target = localTarget;
  79808. }
  79809. }
  79810. }
  79811. var zaxis = BoneLookController._tmpVecs[5];
  79812. var xaxis = BoneLookController._tmpVecs[6];
  79813. var yaxis = BoneLookController._tmpVecs[7];
  79814. var _tmpQuat = BoneLookController._tmpQuat;
  79815. target.subtractToRef(bonePos, zaxis);
  79816. zaxis.normalize();
  79817. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79818. xaxis.normalize();
  79819. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79820. yaxis.normalize();
  79821. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79822. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79823. return;
  79824. }
  79825. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79826. return;
  79827. }
  79828. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79829. return;
  79830. }
  79831. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79832. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79833. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79834. }
  79835. if (this.slerpAmount < 1) {
  79836. if (!this._slerping) {
  79837. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79838. }
  79839. if (this._transformYawPitch) {
  79840. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79841. }
  79842. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79843. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79844. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79845. this._slerping = true;
  79846. }
  79847. else {
  79848. if (this._transformYawPitch) {
  79849. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79850. }
  79851. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79852. this._slerping = false;
  79853. }
  79854. };
  79855. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79856. var angDiff = ang2 - ang1;
  79857. angDiff %= Math.PI * 2;
  79858. if (angDiff > Math.PI) {
  79859. angDiff -= Math.PI * 2;
  79860. }
  79861. else if (angDiff < -Math.PI) {
  79862. angDiff += Math.PI * 2;
  79863. }
  79864. return angDiff;
  79865. };
  79866. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79867. ang1 %= (2 * Math.PI);
  79868. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79869. ang2 %= (2 * Math.PI);
  79870. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79871. var ab = 0;
  79872. if (ang1 < ang2) {
  79873. ab = ang2 - ang1;
  79874. }
  79875. else {
  79876. ab = ang1 - ang2;
  79877. }
  79878. if (ab > Math.PI) {
  79879. ab = Math.PI * 2 - ab;
  79880. }
  79881. return ab;
  79882. };
  79883. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79884. ang %= (2 * Math.PI);
  79885. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79886. ang1 %= (2 * Math.PI);
  79887. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79888. ang2 %= (2 * Math.PI);
  79889. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79890. if (ang1 < ang2) {
  79891. if (ang > ang1 && ang < ang2) {
  79892. return true;
  79893. }
  79894. }
  79895. else {
  79896. if (ang > ang2 && ang < ang1) {
  79897. return true;
  79898. }
  79899. }
  79900. return false;
  79901. };
  79902. 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()];
  79903. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79904. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79905. return BoneLookController;
  79906. }());
  79907. BABYLON.BoneLookController = BoneLookController;
  79908. })(BABYLON || (BABYLON = {}));
  79909. //# sourceMappingURL=babylon.boneLookController.js.map
  79910. var BABYLON;
  79911. (function (BABYLON) {
  79912. /**
  79913. * Class used to handle skinning animations
  79914. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79915. */
  79916. var Skeleton = /** @class */ (function () {
  79917. /**
  79918. * Creates a new skeleton
  79919. * @param name defines the skeleton name
  79920. * @param id defines the skeleton Id
  79921. * @param scene defines the hosting scene
  79922. */
  79923. function Skeleton(
  79924. /** defines the skeleton name */
  79925. name,
  79926. /** defines the skeleton Id */
  79927. id, scene) {
  79928. this.name = name;
  79929. this.id = id;
  79930. /**
  79931. * Gets the list of child bones
  79932. */
  79933. this.bones = new Array();
  79934. /**
  79935. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79936. */
  79937. this.needInitialSkinMatrix = false;
  79938. this._isDirty = true;
  79939. this._meshesWithPoseMatrix = new Array();
  79940. this._identity = BABYLON.Matrix.Identity();
  79941. this._ranges = {};
  79942. this._lastAbsoluteTransformsUpdateId = -1;
  79943. /**
  79944. * Specifies if the skeleton should be serialized
  79945. */
  79946. this.doNotSerialize = false;
  79947. this._animationPropertiesOverride = null;
  79948. // Events
  79949. /**
  79950. * An observable triggered before computing the skeleton's matrices
  79951. */
  79952. this.onBeforeComputeObservable = new BABYLON.Observable();
  79953. this.bones = [];
  79954. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79955. scene.skeletons.push(this);
  79956. //make sure it will recalculate the matrix next time prepare is called.
  79957. this._isDirty = true;
  79958. }
  79959. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79960. /**
  79961. * Gets or sets the animation properties override
  79962. */
  79963. get: function () {
  79964. if (!this._animationPropertiesOverride) {
  79965. return this._scene.animationPropertiesOverride;
  79966. }
  79967. return this._animationPropertiesOverride;
  79968. },
  79969. set: function (value) {
  79970. this._animationPropertiesOverride = value;
  79971. },
  79972. enumerable: true,
  79973. configurable: true
  79974. });
  79975. // Members
  79976. /**
  79977. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79978. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79979. * @returns a Float32Array containing matrices data
  79980. */
  79981. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79982. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79983. return mesh._bonesTransformMatrices;
  79984. }
  79985. if (!this._transformMatrices) {
  79986. this.prepare();
  79987. }
  79988. return this._transformMatrices;
  79989. };
  79990. /**
  79991. * Gets the current hosting scene
  79992. * @returns a scene object
  79993. */
  79994. Skeleton.prototype.getScene = function () {
  79995. return this._scene;
  79996. };
  79997. // Methods
  79998. /**
  79999. * Gets a string representing the current skeleton data
  80000. * @param fullDetails defines a boolean indicating if we want a verbose version
  80001. * @returns a string representing the current skeleton data
  80002. */
  80003. Skeleton.prototype.toString = function (fullDetails) {
  80004. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80005. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80006. if (fullDetails) {
  80007. ret += ", Ranges: {";
  80008. var first = true;
  80009. for (var name_1 in this._ranges) {
  80010. if (first) {
  80011. ret += ", ";
  80012. first = false;
  80013. }
  80014. ret += name_1;
  80015. }
  80016. ret += "}";
  80017. }
  80018. return ret;
  80019. };
  80020. /**
  80021. * Get bone's index searching by name
  80022. * @param name defines bone's name to search for
  80023. * @return the indice of the bone. Returns -1 if not found
  80024. */
  80025. Skeleton.prototype.getBoneIndexByName = function (name) {
  80026. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80027. if (this.bones[boneIndex].name === name) {
  80028. return boneIndex;
  80029. }
  80030. }
  80031. return -1;
  80032. };
  80033. /**
  80034. * Creater a new animation range
  80035. * @param name defines the name of the range
  80036. * @param from defines the start key
  80037. * @param to defines the end key
  80038. */
  80039. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80040. // check name not already in use
  80041. if (!this._ranges[name]) {
  80042. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80043. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80044. if (this.bones[i].animations[0]) {
  80045. this.bones[i].animations[0].createRange(name, from, to);
  80046. }
  80047. }
  80048. }
  80049. };
  80050. /**
  80051. * Delete a specific animation range
  80052. * @param name defines the name of the range
  80053. * @param deleteFrames defines if frames must be removed as well
  80054. */
  80055. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80056. if (deleteFrames === void 0) { deleteFrames = true; }
  80057. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80058. if (this.bones[i].animations[0]) {
  80059. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80060. }
  80061. }
  80062. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80063. };
  80064. /**
  80065. * Gets a specific animation range
  80066. * @param name defines the name of the range to look for
  80067. * @returns the requested animation range or null if not found
  80068. */
  80069. Skeleton.prototype.getAnimationRange = function (name) {
  80070. return this._ranges[name];
  80071. };
  80072. /**
  80073. * Gets the list of all animation ranges defined on this skeleton
  80074. * @returns an array
  80075. */
  80076. Skeleton.prototype.getAnimationRanges = function () {
  80077. var animationRanges = [];
  80078. var name;
  80079. var i = 0;
  80080. for (name in this._ranges) {
  80081. animationRanges[i] = this._ranges[name];
  80082. i++;
  80083. }
  80084. return animationRanges;
  80085. };
  80086. /**
  80087. * Copy animation range from a source skeleton.
  80088. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80089. * @param source defines the source skeleton
  80090. * @param name defines the name of the range to copy
  80091. * @param rescaleAsRequired defines if rescaling must be applied if required
  80092. * @returns true if operation was successful
  80093. */
  80094. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80095. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80096. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80097. return false;
  80098. }
  80099. var ret = true;
  80100. var frameOffset = this._getHighestAnimationFrame() + 1;
  80101. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80102. var boneDict = {};
  80103. var sourceBones = source.bones;
  80104. var nBones;
  80105. var i;
  80106. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80107. boneDict[sourceBones[i].name] = sourceBones[i];
  80108. }
  80109. if (this.bones.length !== sourceBones.length) {
  80110. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80111. ret = false;
  80112. }
  80113. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80114. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80115. var boneName = this.bones[i].name;
  80116. var sourceBone = boneDict[boneName];
  80117. if (sourceBone) {
  80118. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80119. }
  80120. else {
  80121. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80122. ret = false;
  80123. }
  80124. }
  80125. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80126. var range = source.getAnimationRange(name);
  80127. if (range) {
  80128. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80129. }
  80130. return ret;
  80131. };
  80132. /**
  80133. * Forces the skeleton to go to rest pose
  80134. */
  80135. Skeleton.prototype.returnToRest = function () {
  80136. for (var index = 0; index < this.bones.length; index++) {
  80137. this.bones[index].returnToRest();
  80138. }
  80139. };
  80140. Skeleton.prototype._getHighestAnimationFrame = function () {
  80141. var ret = 0;
  80142. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80143. if (this.bones[i].animations[0]) {
  80144. var highest = this.bones[i].animations[0].getHighestFrame();
  80145. if (ret < highest) {
  80146. ret = highest;
  80147. }
  80148. }
  80149. }
  80150. return ret;
  80151. };
  80152. /**
  80153. * Begin a specific animation range
  80154. * @param name defines the name of the range to start
  80155. * @param loop defines if looping must be turned on (false by default)
  80156. * @param speedRatio defines the speed ratio to apply (1 by default)
  80157. * @param onAnimationEnd defines a callback which will be called when animation will end
  80158. * @returns a new animatable
  80159. */
  80160. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80161. var range = this.getAnimationRange(name);
  80162. if (!range) {
  80163. return null;
  80164. }
  80165. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80166. };
  80167. /** @hidden */
  80168. Skeleton.prototype._markAsDirty = function () {
  80169. this._isDirty = true;
  80170. };
  80171. /** @hidden */
  80172. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80173. this._meshesWithPoseMatrix.push(mesh);
  80174. };
  80175. /** @hidden */
  80176. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80177. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80178. if (index > -1) {
  80179. this._meshesWithPoseMatrix.splice(index, 1);
  80180. }
  80181. };
  80182. /** @hidden */
  80183. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80184. this.onBeforeComputeObservable.notifyObservers(this);
  80185. for (var index = 0; index < this.bones.length; index++) {
  80186. var bone = this.bones[index];
  80187. var parentBone = bone.getParent();
  80188. if (parentBone) {
  80189. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80190. }
  80191. else {
  80192. if (initialSkinMatrix) {
  80193. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80194. }
  80195. else {
  80196. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80197. }
  80198. }
  80199. if (bone._index !== -1) {
  80200. var mappedIndex = bone._index === null ? index : bone._index;
  80201. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80202. }
  80203. }
  80204. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80205. };
  80206. /**
  80207. * Build all resources required to render a skeleton
  80208. */
  80209. Skeleton.prototype.prepare = function () {
  80210. if (!this._isDirty) {
  80211. return;
  80212. }
  80213. if (this.needInitialSkinMatrix) {
  80214. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80215. var mesh = this._meshesWithPoseMatrix[index];
  80216. var poseMatrix = mesh.getPoseMatrix();
  80217. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80218. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80219. }
  80220. if (this._synchronizedWithMesh !== mesh) {
  80221. this._synchronizedWithMesh = mesh;
  80222. // Prepare bones
  80223. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80224. var bone = this.bones[boneIndex];
  80225. if (!bone.getParent()) {
  80226. var matrix = bone.getBaseMatrix();
  80227. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80228. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80229. }
  80230. }
  80231. }
  80232. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80233. }
  80234. }
  80235. else {
  80236. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80237. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80238. }
  80239. this._computeTransformMatrices(this._transformMatrices, null);
  80240. }
  80241. this._isDirty = false;
  80242. this._scene._activeBones.addCount(this.bones.length, false);
  80243. };
  80244. /**
  80245. * Gets the list of animatables currently running for this skeleton
  80246. * @returns an array of animatables
  80247. */
  80248. Skeleton.prototype.getAnimatables = function () {
  80249. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80250. this._animatables = [];
  80251. for (var index = 0; index < this.bones.length; index++) {
  80252. this._animatables.push(this.bones[index]);
  80253. }
  80254. }
  80255. return this._animatables;
  80256. };
  80257. /**
  80258. * Clone the current skeleton
  80259. * @param name defines the name of the new skeleton
  80260. * @param id defines the id of the enw skeleton
  80261. * @returns the new skeleton
  80262. */
  80263. Skeleton.prototype.clone = function (name, id) {
  80264. var result = new Skeleton(name, id || name, this._scene);
  80265. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80266. for (var index = 0; index < this.bones.length; index++) {
  80267. var source = this.bones[index];
  80268. var parentBone = null;
  80269. var parent_1 = source.getParent();
  80270. if (parent_1) {
  80271. var parentIndex = this.bones.indexOf(parent_1);
  80272. parentBone = result.bones[parentIndex];
  80273. }
  80274. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80275. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80276. }
  80277. if (this._ranges) {
  80278. result._ranges = {};
  80279. for (var rangeName in this._ranges) {
  80280. var range = this._ranges[rangeName];
  80281. if (range) {
  80282. result._ranges[rangeName] = range.clone();
  80283. }
  80284. }
  80285. }
  80286. this._isDirty = true;
  80287. return result;
  80288. };
  80289. /**
  80290. * Enable animation blending for this skeleton
  80291. * @param blendingSpeed defines the blending speed to apply
  80292. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80293. */
  80294. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80295. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80296. this.bones.forEach(function (bone) {
  80297. bone.animations.forEach(function (animation) {
  80298. animation.enableBlending = true;
  80299. animation.blendingSpeed = blendingSpeed;
  80300. });
  80301. });
  80302. };
  80303. /**
  80304. * Releases all resources associated with the current skeleton
  80305. */
  80306. Skeleton.prototype.dispose = function () {
  80307. this._meshesWithPoseMatrix = [];
  80308. // Animations
  80309. this.getScene().stopAnimation(this);
  80310. // Remove from scene
  80311. this.getScene().removeSkeleton(this);
  80312. };
  80313. /**
  80314. * Serialize the skeleton in a JSON object
  80315. * @returns a JSON object
  80316. */
  80317. Skeleton.prototype.serialize = function () {
  80318. var serializationObject = {};
  80319. serializationObject.name = this.name;
  80320. serializationObject.id = this.id;
  80321. if (this.dimensionsAtRest) {
  80322. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80323. }
  80324. serializationObject.bones = [];
  80325. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80326. for (var index = 0; index < this.bones.length; index++) {
  80327. var bone = this.bones[index];
  80328. var parent_2 = bone.getParent();
  80329. var serializedBone = {
  80330. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80331. name: bone.name,
  80332. matrix: bone.getBaseMatrix().toArray(),
  80333. rest: bone.getRestPose().toArray()
  80334. };
  80335. serializationObject.bones.push(serializedBone);
  80336. if (bone.length) {
  80337. serializedBone.length = bone.length;
  80338. }
  80339. if (bone.metadata) {
  80340. serializedBone.metadata = bone.metadata;
  80341. }
  80342. if (bone.animations && bone.animations.length > 0) {
  80343. serializedBone.animation = bone.animations[0].serialize();
  80344. }
  80345. serializationObject.ranges = [];
  80346. for (var name in this._ranges) {
  80347. var source = this._ranges[name];
  80348. if (!source) {
  80349. continue;
  80350. }
  80351. var range = {};
  80352. range.name = name;
  80353. range.from = source.from;
  80354. range.to = source.to;
  80355. serializationObject.ranges.push(range);
  80356. }
  80357. }
  80358. return serializationObject;
  80359. };
  80360. /**
  80361. * Creates a new skeleton from serialized data
  80362. * @param parsedSkeleton defines the serialized data
  80363. * @param scene defines the hosting scene
  80364. * @returns a new skeleton
  80365. */
  80366. Skeleton.Parse = function (parsedSkeleton, scene) {
  80367. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80368. if (parsedSkeleton.dimensionsAtRest) {
  80369. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80370. }
  80371. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80372. var index;
  80373. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80374. var parsedBone = parsedSkeleton.bones[index];
  80375. var parentBone = null;
  80376. if (parsedBone.parentBoneIndex > -1) {
  80377. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80378. }
  80379. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80380. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80381. if (parsedBone.length) {
  80382. bone.length = parsedBone.length;
  80383. }
  80384. if (parsedBone.metadata) {
  80385. bone.metadata = parsedBone.metadata;
  80386. }
  80387. if (parsedBone.animation) {
  80388. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80389. }
  80390. }
  80391. // placed after bones, so createAnimationRange can cascade down
  80392. if (parsedSkeleton.ranges) {
  80393. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80394. var data = parsedSkeleton.ranges[index];
  80395. skeleton.createAnimationRange(data.name, data.from, data.to);
  80396. }
  80397. }
  80398. return skeleton;
  80399. };
  80400. /**
  80401. * Compute all node absolute transforms
  80402. * @param forceUpdate defines if computation must be done even if cache is up to date
  80403. */
  80404. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80405. if (forceUpdate === void 0) { forceUpdate = false; }
  80406. var renderId = this._scene.getRenderId();
  80407. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80408. this.bones[0].computeAbsoluteTransforms();
  80409. this._lastAbsoluteTransformsUpdateId = renderId;
  80410. }
  80411. };
  80412. /**
  80413. * Gets the root pose matrix
  80414. * @returns a matrix
  80415. */
  80416. Skeleton.prototype.getPoseMatrix = function () {
  80417. var poseMatrix = null;
  80418. if (this._meshesWithPoseMatrix.length > 0) {
  80419. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80420. }
  80421. return poseMatrix;
  80422. };
  80423. /**
  80424. * Sorts bones per internal index
  80425. */
  80426. Skeleton.prototype.sortBones = function () {
  80427. var bones = new Array();
  80428. var visited = new Array(this.bones.length);
  80429. for (var index = 0; index < this.bones.length; index++) {
  80430. this._sortBones(index, bones, visited);
  80431. }
  80432. this.bones = bones;
  80433. };
  80434. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80435. if (visited[index]) {
  80436. return;
  80437. }
  80438. visited[index] = true;
  80439. var bone = this.bones[index];
  80440. if (bone._index === undefined) {
  80441. bone._index = index;
  80442. }
  80443. var parentBone = bone.getParent();
  80444. if (parentBone) {
  80445. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80446. }
  80447. bones.push(bone);
  80448. };
  80449. return Skeleton;
  80450. }());
  80451. BABYLON.Skeleton = Skeleton;
  80452. })(BABYLON || (BABYLON = {}));
  80453. //# sourceMappingURL=babylon.skeleton.js.map
  80454. var BABYLON;
  80455. (function (BABYLON) {
  80456. var SphericalPolynomial = /** @class */ (function () {
  80457. function SphericalPolynomial() {
  80458. this.x = BABYLON.Vector3.Zero();
  80459. this.y = BABYLON.Vector3.Zero();
  80460. this.z = BABYLON.Vector3.Zero();
  80461. this.xx = BABYLON.Vector3.Zero();
  80462. this.yy = BABYLON.Vector3.Zero();
  80463. this.zz = BABYLON.Vector3.Zero();
  80464. this.xy = BABYLON.Vector3.Zero();
  80465. this.yz = BABYLON.Vector3.Zero();
  80466. this.zx = BABYLON.Vector3.Zero();
  80467. }
  80468. SphericalPolynomial.prototype.addAmbient = function (color) {
  80469. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80470. this.xx = this.xx.add(colorVector);
  80471. this.yy = this.yy.add(colorVector);
  80472. this.zz = this.zz.add(colorVector);
  80473. };
  80474. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80475. var result = new SphericalPolynomial();
  80476. result.x = harmonics.L11.scale(1.02333);
  80477. result.y = harmonics.L1_1.scale(1.02333);
  80478. result.z = harmonics.L10.scale(1.02333);
  80479. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80480. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80481. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80482. result.yz = harmonics.L2_1.scale(0.858086);
  80483. result.zx = harmonics.L21.scale(0.858086);
  80484. result.xy = harmonics.L2_2.scale(0.858086);
  80485. result.scale(1.0 / Math.PI);
  80486. return result;
  80487. };
  80488. SphericalPolynomial.prototype.scale = function (scale) {
  80489. this.x = this.x.scale(scale);
  80490. this.y = this.y.scale(scale);
  80491. this.z = this.z.scale(scale);
  80492. this.xx = this.xx.scale(scale);
  80493. this.yy = this.yy.scale(scale);
  80494. this.zz = this.zz.scale(scale);
  80495. this.yz = this.yz.scale(scale);
  80496. this.zx = this.zx.scale(scale);
  80497. this.xy = this.xy.scale(scale);
  80498. };
  80499. return SphericalPolynomial;
  80500. }());
  80501. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80502. var SphericalHarmonics = /** @class */ (function () {
  80503. function SphericalHarmonics() {
  80504. this.L00 = BABYLON.Vector3.Zero();
  80505. this.L1_1 = BABYLON.Vector3.Zero();
  80506. this.L10 = BABYLON.Vector3.Zero();
  80507. this.L11 = BABYLON.Vector3.Zero();
  80508. this.L2_2 = BABYLON.Vector3.Zero();
  80509. this.L2_1 = BABYLON.Vector3.Zero();
  80510. this.L20 = BABYLON.Vector3.Zero();
  80511. this.L21 = BABYLON.Vector3.Zero();
  80512. this.L22 = BABYLON.Vector3.Zero();
  80513. }
  80514. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80515. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80516. var c = colorVector.scale(deltaSolidAngle);
  80517. this.L00 = this.L00.add(c.scale(0.282095));
  80518. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80519. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80520. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80521. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80522. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80523. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80524. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80525. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80526. };
  80527. SphericalHarmonics.prototype.scale = function (scale) {
  80528. this.L00 = this.L00.scale(scale);
  80529. this.L1_1 = this.L1_1.scale(scale);
  80530. this.L10 = this.L10.scale(scale);
  80531. this.L11 = this.L11.scale(scale);
  80532. this.L2_2 = this.L2_2.scale(scale);
  80533. this.L2_1 = this.L2_1.scale(scale);
  80534. this.L20 = this.L20.scale(scale);
  80535. this.L21 = this.L21.scale(scale);
  80536. this.L22 = this.L22.scale(scale);
  80537. };
  80538. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80539. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80540. //
  80541. // E_lm = A_l * L_lm
  80542. //
  80543. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80544. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80545. // the scaling factors are given in equation 9.
  80546. // Constant (Band 0)
  80547. this.L00 = this.L00.scale(3.141593);
  80548. // Linear (Band 1)
  80549. this.L1_1 = this.L1_1.scale(2.094395);
  80550. this.L10 = this.L10.scale(2.094395);
  80551. this.L11 = this.L11.scale(2.094395);
  80552. // Quadratic (Band 2)
  80553. this.L2_2 = this.L2_2.scale(0.785398);
  80554. this.L2_1 = this.L2_1.scale(0.785398);
  80555. this.L20 = this.L20.scale(0.785398);
  80556. this.L21 = this.L21.scale(0.785398);
  80557. this.L22 = this.L22.scale(0.785398);
  80558. };
  80559. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80560. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80561. // L = (1/pi) * E * rho
  80562. //
  80563. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80564. this.scale(1.0 / Math.PI);
  80565. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80566. // (The pixel shader must apply albedo after texture fetches, etc).
  80567. };
  80568. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80569. var result = new SphericalHarmonics();
  80570. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80571. result.L1_1 = polynomial.y.scale(0.977204);
  80572. result.L10 = polynomial.z.scale(0.977204);
  80573. result.L11 = polynomial.x.scale(0.977204);
  80574. result.L2_2 = polynomial.xy.scale(1.16538);
  80575. result.L2_1 = polynomial.yz.scale(1.16538);
  80576. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80577. result.L21 = polynomial.zx.scale(1.16538);
  80578. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80579. result.scale(Math.PI);
  80580. return result;
  80581. };
  80582. return SphericalHarmonics;
  80583. }());
  80584. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80585. })(BABYLON || (BABYLON = {}));
  80586. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80587. var BABYLON;
  80588. (function (BABYLON) {
  80589. var FileFaceOrientation = /** @class */ (function () {
  80590. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80591. this.name = name;
  80592. this.worldAxisForNormal = worldAxisForNormal;
  80593. this.worldAxisForFileX = worldAxisForFileX;
  80594. this.worldAxisForFileY = worldAxisForFileY;
  80595. }
  80596. return FileFaceOrientation;
  80597. }());
  80598. ;
  80599. /**
  80600. * Helper class dealing with the extraction of spherical polynomial dataArray
  80601. * from a cube map.
  80602. */
  80603. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80604. function CubeMapToSphericalPolynomialTools() {
  80605. }
  80606. /**
  80607. * Converts a texture to the according Spherical Polynomial data.
  80608. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80609. *
  80610. * @param texture The texture to extract the information from.
  80611. * @return The Spherical Polynomial data.
  80612. */
  80613. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80614. if (!texture.isCube) {
  80615. // Only supports cube Textures currently.
  80616. return null;
  80617. }
  80618. var size = texture.getSize().width;
  80619. var right = texture.readPixels(0);
  80620. var left = texture.readPixels(1);
  80621. var up;
  80622. var down;
  80623. if (texture.isRenderTarget) {
  80624. up = texture.readPixels(3);
  80625. down = texture.readPixels(2);
  80626. }
  80627. else {
  80628. up = texture.readPixels(2);
  80629. down = texture.readPixels(3);
  80630. }
  80631. var front = texture.readPixels(4);
  80632. var back = texture.readPixels(5);
  80633. var gammaSpace = texture.gammaSpace;
  80634. // Always read as RGBA.
  80635. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80636. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80637. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80638. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80639. }
  80640. var cubeInfo = {
  80641. size: size,
  80642. right: right,
  80643. left: left,
  80644. up: up,
  80645. down: down,
  80646. front: front,
  80647. back: back,
  80648. format: format,
  80649. type: type,
  80650. gammaSpace: gammaSpace,
  80651. };
  80652. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80653. };
  80654. /**
  80655. * Converts a cubemap to the according Spherical Polynomial data.
  80656. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80657. *
  80658. * @param cubeInfo The Cube map to extract the information from.
  80659. * @return The Spherical Polynomial data.
  80660. */
  80661. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80662. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80663. var totalSolidAngle = 0.0;
  80664. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80665. var du = 2.0 / cubeInfo.size;
  80666. var dv = du;
  80667. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80668. var minUV = du * 0.5 - 1.0;
  80669. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80670. var fileFace = this.FileFaces[faceIndex];
  80671. var dataArray = cubeInfo[fileFace.name];
  80672. var v = minUV;
  80673. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80674. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80675. // Because SP is still linear, so summation is fine in that basis.
  80676. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80677. for (var y = 0; y < cubeInfo.size; y++) {
  80678. var u = minUV;
  80679. for (var x = 0; x < cubeInfo.size; x++) {
  80680. // World direction (not normalised)
  80681. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80682. worldDirection.normalize();
  80683. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80684. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80685. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80686. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80687. // Handle Integer types.
  80688. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80689. r /= 255;
  80690. g /= 255;
  80691. b /= 255;
  80692. }
  80693. // Handle Gamma space textures.
  80694. if (cubeInfo.gammaSpace) {
  80695. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80696. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80697. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80698. }
  80699. var color = new BABYLON.Color3(r, g, b);
  80700. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80701. totalSolidAngle += deltaSolidAngle;
  80702. u += du;
  80703. }
  80704. v += dv;
  80705. }
  80706. }
  80707. // Solid angle for entire sphere is 4*pi
  80708. var sphereSolidAngle = 4.0 * Math.PI;
  80709. // Adjust the solid angle to allow for how many faces we processed.
  80710. var facesProcessed = 6.0;
  80711. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80712. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80713. // This is needed because the numerical integration over the cube uses a
  80714. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80715. // and also to compensate for accumulative error due to float precision in the summation.
  80716. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80717. sphericalHarmonics.scale(correctionFactor);
  80718. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80719. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80720. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80721. };
  80722. CubeMapToSphericalPolynomialTools.FileFaces = [
  80723. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80724. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80725. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80726. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80727. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80728. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80729. ];
  80730. return CubeMapToSphericalPolynomialTools;
  80731. }());
  80732. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80733. })(BABYLON || (BABYLON = {}));
  80734. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80735. var BABYLON;
  80736. (function (BABYLON) {
  80737. /**
  80738. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80739. */
  80740. var PanoramaToCubeMapTools = /** @class */ (function () {
  80741. function PanoramaToCubeMapTools() {
  80742. }
  80743. /**
  80744. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80745. *
  80746. * @param float32Array The source data.
  80747. * @param inputWidth The width of the input panorama.
  80748. * @param inputhHeight The height of the input panorama.
  80749. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80750. * @return The cubemap data
  80751. */
  80752. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80753. if (!float32Array) {
  80754. throw "ConvertPanoramaToCubemap: input cannot be null";
  80755. }
  80756. if (float32Array.length != inputWidth * inputHeight * 3) {
  80757. throw "ConvertPanoramaToCubemap: input size is wrong";
  80758. }
  80759. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80760. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80761. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80762. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80763. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80764. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80765. return {
  80766. front: textureFront,
  80767. back: textureBack,
  80768. left: textureLeft,
  80769. right: textureRight,
  80770. up: textureUp,
  80771. down: textureDown,
  80772. size: size,
  80773. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80774. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80775. gammaSpace: false,
  80776. };
  80777. };
  80778. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80779. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80780. var textureArray = new Float32Array(buffer);
  80781. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80782. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80783. var dy = 1 / texSize;
  80784. var fy = 0;
  80785. for (var y = 0; y < texSize; y++) {
  80786. var xv1 = faceData[0];
  80787. var xv2 = faceData[2];
  80788. for (var x = 0; x < texSize; x++) {
  80789. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80790. v.normalize();
  80791. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80792. // 3 channels per pixels
  80793. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80794. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80795. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80796. xv1 = xv1.add(rotDX1);
  80797. xv2 = xv2.add(rotDX2);
  80798. }
  80799. fy += dy;
  80800. }
  80801. return textureArray;
  80802. };
  80803. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80804. var theta = Math.atan2(vDir.z, vDir.x);
  80805. var phi = Math.acos(vDir.y);
  80806. while (theta < -Math.PI)
  80807. theta += 2 * Math.PI;
  80808. while (theta > Math.PI)
  80809. theta -= 2 * Math.PI;
  80810. var dx = theta / Math.PI;
  80811. var dy = phi / Math.PI;
  80812. // recenter.
  80813. dx = dx * 0.5 + 0.5;
  80814. var px = Math.round(dx * inputWidth);
  80815. if (px < 0)
  80816. px = 0;
  80817. else if (px >= inputWidth)
  80818. px = inputWidth - 1;
  80819. var py = Math.round(dy * inputHeight);
  80820. if (py < 0)
  80821. py = 0;
  80822. else if (py >= inputHeight)
  80823. py = inputHeight - 1;
  80824. var inputY = (inputHeight - py - 1);
  80825. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80826. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80827. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80828. return {
  80829. r: r,
  80830. g: g,
  80831. b: b
  80832. };
  80833. };
  80834. PanoramaToCubeMapTools.FACE_FRONT = [
  80835. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80836. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80837. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80838. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80839. ];
  80840. PanoramaToCubeMapTools.FACE_BACK = [
  80841. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80842. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80843. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80844. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80845. ];
  80846. PanoramaToCubeMapTools.FACE_RIGHT = [
  80847. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80848. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80849. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80850. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80851. ];
  80852. PanoramaToCubeMapTools.FACE_LEFT = [
  80853. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80854. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80855. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80856. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80857. ];
  80858. PanoramaToCubeMapTools.FACE_DOWN = [
  80859. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80860. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80861. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80862. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80863. ];
  80864. PanoramaToCubeMapTools.FACE_UP = [
  80865. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80866. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80867. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80868. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80869. ];
  80870. return PanoramaToCubeMapTools;
  80871. }());
  80872. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80873. })(BABYLON || (BABYLON = {}));
  80874. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80875. var BABYLON;
  80876. (function (BABYLON) {
  80877. ;
  80878. /**
  80879. * This groups tools to convert HDR texture to native colors array.
  80880. */
  80881. var HDRTools = /** @class */ (function () {
  80882. function HDRTools() {
  80883. }
  80884. HDRTools.Ldexp = function (mantissa, exponent) {
  80885. if (exponent > 1023) {
  80886. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80887. }
  80888. if (exponent < -1074) {
  80889. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80890. }
  80891. return mantissa * Math.pow(2, exponent);
  80892. };
  80893. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80894. if (exponent > 0) { /*nonzero pixel*/
  80895. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80896. float32array[index + 0] = red * exponent;
  80897. float32array[index + 1] = green * exponent;
  80898. float32array[index + 2] = blue * exponent;
  80899. }
  80900. else {
  80901. float32array[index + 0] = 0;
  80902. float32array[index + 1] = 0;
  80903. float32array[index + 2] = 0;
  80904. }
  80905. };
  80906. HDRTools.readStringLine = function (uint8array, startIndex) {
  80907. var line = "";
  80908. var character = "";
  80909. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80910. character = String.fromCharCode(uint8array[i]);
  80911. if (character == "\n") {
  80912. break;
  80913. }
  80914. line += character;
  80915. }
  80916. return line;
  80917. };
  80918. /**
  80919. * Reads header information from an RGBE texture stored in a native array.
  80920. * More information on this format are available here:
  80921. * https://en.wikipedia.org/wiki/RGBE_image_format
  80922. *
  80923. * @param uint8array The binary file stored in native array.
  80924. * @return The header information.
  80925. */
  80926. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80927. var height = 0;
  80928. var width = 0;
  80929. var line = this.readStringLine(uint8array, 0);
  80930. if (line[0] != '#' || line[1] != '?') {
  80931. throw "Bad HDR Format.";
  80932. }
  80933. var endOfHeader = false;
  80934. var findFormat = false;
  80935. var lineIndex = 0;
  80936. do {
  80937. lineIndex += (line.length + 1);
  80938. line = this.readStringLine(uint8array, lineIndex);
  80939. if (line == "FORMAT=32-bit_rle_rgbe") {
  80940. findFormat = true;
  80941. }
  80942. else if (line.length == 0) {
  80943. endOfHeader = true;
  80944. }
  80945. } while (!endOfHeader);
  80946. if (!findFormat) {
  80947. throw "HDR Bad header format, unsupported FORMAT";
  80948. }
  80949. lineIndex += (line.length + 1);
  80950. line = this.readStringLine(uint8array, lineIndex);
  80951. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80952. var match = sizeRegexp.exec(line);
  80953. // TODO. Support +Y and -X if needed.
  80954. if (!match || match.length < 3) {
  80955. throw "HDR Bad header format, no size";
  80956. }
  80957. width = parseInt(match[2]);
  80958. height = parseInt(match[1]);
  80959. if (width < 8 || width > 0x7fff) {
  80960. throw "HDR Bad header format, unsupported size";
  80961. }
  80962. lineIndex += (line.length + 1);
  80963. return {
  80964. height: height,
  80965. width: width,
  80966. dataPosition: lineIndex
  80967. };
  80968. };
  80969. /**
  80970. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80971. * This RGBE texture needs to store the information as a panorama.
  80972. *
  80973. * More information on this format are available here:
  80974. * https://en.wikipedia.org/wiki/RGBE_image_format
  80975. *
  80976. * @param buffer The binary file stored in an array buffer.
  80977. * @param size The expected size of the extracted cubemap.
  80978. * @return The Cube Map information.
  80979. */
  80980. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80981. var uint8array = new Uint8Array(buffer);
  80982. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80983. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80984. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80985. return cubeMapData;
  80986. };
  80987. /**
  80988. * Returns the pixels data extracted from an RGBE texture.
  80989. * This pixels will be stored left to right up to down in the R G B order in one array.
  80990. *
  80991. * More information on this format are available here:
  80992. * https://en.wikipedia.org/wiki/RGBE_image_format
  80993. *
  80994. * @param uint8array The binary file stored in an array buffer.
  80995. * @param hdrInfo The header information of the file.
  80996. * @return The pixels data in RGB right to left up to down order.
  80997. */
  80998. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80999. // Keep for multi format supports.
  81000. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81001. };
  81002. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81003. var num_scanlines = hdrInfo.height;
  81004. var scanline_width = hdrInfo.width;
  81005. var a, b, c, d, count;
  81006. var dataIndex = hdrInfo.dataPosition;
  81007. var index = 0, endIndex = 0, i = 0;
  81008. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81009. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81010. // 3 channels of 4 bytes per pixel in float.
  81011. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81012. var resultArray = new Float32Array(resultBuffer);
  81013. // read in each successive scanline
  81014. while (num_scanlines > 0) {
  81015. a = uint8array[dataIndex++];
  81016. b = uint8array[dataIndex++];
  81017. c = uint8array[dataIndex++];
  81018. d = uint8array[dataIndex++];
  81019. if (a != 2 || b != 2 || (c & 0x80)) {
  81020. // this file is not run length encoded
  81021. throw "HDR Bad header format, not RLE";
  81022. }
  81023. if (((c << 8) | d) != scanline_width) {
  81024. throw "HDR Bad header format, wrong scan line width";
  81025. }
  81026. index = 0;
  81027. // read each of the four channels for the scanline into the buffer
  81028. for (i = 0; i < 4; i++) {
  81029. endIndex = (i + 1) * scanline_width;
  81030. while (index < endIndex) {
  81031. a = uint8array[dataIndex++];
  81032. b = uint8array[dataIndex++];
  81033. if (a > 128) {
  81034. // a run of the same value
  81035. count = a - 128;
  81036. if ((count == 0) || (count > endIndex - index)) {
  81037. throw "HDR Bad Format, bad scanline data (run)";
  81038. }
  81039. while (count-- > 0) {
  81040. scanLineArray[index++] = b;
  81041. }
  81042. }
  81043. else {
  81044. // a non-run
  81045. count = a;
  81046. if ((count == 0) || (count > endIndex - index)) {
  81047. throw "HDR Bad Format, bad scanline data (non-run)";
  81048. }
  81049. scanLineArray[index++] = b;
  81050. if (--count > 0) {
  81051. for (var j = 0; j < count; j++) {
  81052. scanLineArray[index++] = uint8array[dataIndex++];
  81053. }
  81054. }
  81055. }
  81056. }
  81057. }
  81058. // now convert data from buffer into floats
  81059. for (i = 0; i < scanline_width; i++) {
  81060. a = scanLineArray[i];
  81061. b = scanLineArray[i + scanline_width];
  81062. c = scanLineArray[i + 2 * scanline_width];
  81063. d = scanLineArray[i + 3 * scanline_width];
  81064. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81065. }
  81066. num_scanlines--;
  81067. }
  81068. return resultArray;
  81069. };
  81070. return HDRTools;
  81071. }());
  81072. BABYLON.HDRTools = HDRTools;
  81073. })(BABYLON || (BABYLON = {}));
  81074. //# sourceMappingURL=babylon.hdr.js.map
  81075. var BABYLON;
  81076. (function (BABYLON) {
  81077. /**
  81078. * Sets of helpers addressing the serialization and deserialization of environment texture
  81079. * stored in a BabylonJS env file.
  81080. * Those files are usually stored as .env files.
  81081. */
  81082. var EnvironmentTextureTools = /** @class */ (function () {
  81083. function EnvironmentTextureTools() {
  81084. }
  81085. /**
  81086. * Gets the environment info from an env file.
  81087. * @param data The array buffer containing the .env bytes.
  81088. * @returns the environment file info (the json header) if successfully parsed.
  81089. */
  81090. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81091. var dataView = new DataView(data);
  81092. var pos = 0;
  81093. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81094. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81095. BABYLON.Tools.Error('Not a babylon environment map');
  81096. return null;
  81097. }
  81098. }
  81099. // Read json manifest - collect characters up to null terminator
  81100. var manifestString = '';
  81101. var charCode = 0x00;
  81102. while ((charCode = dataView.getUint8(pos++))) {
  81103. manifestString += String.fromCharCode(charCode);
  81104. }
  81105. var manifest = JSON.parse(manifestString);
  81106. if (manifest.specular) {
  81107. // Extend the header with the position of the payload.
  81108. manifest.specular.specularDataPosition = pos;
  81109. }
  81110. return manifest;
  81111. };
  81112. /**
  81113. * Creates an environment texture from a loaded cube texture.
  81114. * @param texture defines the cube texture to convert in env file
  81115. * @return a promise containing the environment data if succesfull.
  81116. */
  81117. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81118. var _this = this;
  81119. var internalTexture = texture.getInternalTexture();
  81120. if (!internalTexture) {
  81121. return Promise.reject("The cube texture is invalid.");
  81122. }
  81123. if (!texture._prefiltered) {
  81124. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81125. }
  81126. var engine = internalTexture.getEngine();
  81127. if (engine && engine.premultipliedAlpha) {
  81128. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81129. }
  81130. var canvas = engine.getRenderingCanvas();
  81131. if (!canvas) {
  81132. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81133. }
  81134. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81135. if (!engine.getCaps().textureFloatRender) {
  81136. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81137. if (!engine.getCaps().textureHalfFloatRender) {
  81138. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81139. }
  81140. }
  81141. var cubeWidth = internalTexture.width;
  81142. var hostingScene = new BABYLON.Scene(engine);
  81143. var specularTextures = {};
  81144. var promises = [];
  81145. // Read and collect all mipmaps data from the cube.
  81146. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81147. mipmapsCount = Math.round(mipmapsCount);
  81148. var _loop_1 = function (i) {
  81149. var faceWidth = Math.pow(2, mipmapsCount - i);
  81150. var _loop_2 = function (face) {
  81151. var data = texture.readPixels(face, i);
  81152. // Creates a temp texture with the face data.
  81153. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81154. // And rgbdEncode them.
  81155. var promise = new Promise(function (resolve, reject) {
  81156. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  81157. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81158. rgbdPostProcess.onApply = function (effect) {
  81159. effect._bindTexture("textureSampler", tempTexture);
  81160. };
  81161. // As the process needs to happen on the main canvas, keep track of the current size
  81162. var currentW = engine.getRenderWidth();
  81163. var currentH = engine.getRenderHeight();
  81164. // Set the desired size for the texture
  81165. engine.setSize(faceWidth, faceWidth);
  81166. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81167. // Reading datas from WebGL
  81168. canvas.toBlob(function (blob) {
  81169. var fileReader = new FileReader();
  81170. fileReader.onload = function (event) {
  81171. var arrayBuffer = event.target.result;
  81172. specularTextures[i * 6 + face] = arrayBuffer;
  81173. resolve();
  81174. };
  81175. fileReader.readAsArrayBuffer(blob);
  81176. });
  81177. // Reapply the previous canvas size
  81178. engine.setSize(currentW, currentH);
  81179. });
  81180. });
  81181. promises.push(promise);
  81182. };
  81183. // All faces of the cube.
  81184. for (var face = 0; face < 6; face++) {
  81185. _loop_2(face);
  81186. }
  81187. };
  81188. for (var i = 0; i <= mipmapsCount; i++) {
  81189. _loop_1(i);
  81190. }
  81191. // Once all the textures haves been collected as RGBD stored in PNGs
  81192. return Promise.all(promises).then(function () {
  81193. // We can delete the hosting scene keeping track of all the creation objects
  81194. hostingScene.dispose();
  81195. // Creates the json header for the env texture
  81196. var info = {
  81197. version: 1,
  81198. width: cubeWidth,
  81199. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81200. specular: {
  81201. mipmaps: []
  81202. }
  81203. };
  81204. // Sets the specular image data information
  81205. var position = 0;
  81206. for (var i = 0; i <= mipmapsCount; i++) {
  81207. for (var face = 0; face < 6; face++) {
  81208. var byteLength = specularTextures[i * 6 + face].byteLength;
  81209. info.specular.mipmaps.push({
  81210. length: byteLength,
  81211. position: position
  81212. });
  81213. position += byteLength;
  81214. }
  81215. }
  81216. // Encode the JSON as an array buffer
  81217. var infoString = JSON.stringify(info);
  81218. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81219. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81220. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81221. infoView[i] = infoString.charCodeAt(i);
  81222. }
  81223. // Ends up with a null terminator for easier parsing
  81224. infoView[infoString.length] = 0x00;
  81225. // Computes the final required size and creates the storage
  81226. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81227. var finalBuffer = new ArrayBuffer(totalSize);
  81228. var finalBufferView = new Uint8Array(finalBuffer);
  81229. var dataView = new DataView(finalBuffer);
  81230. // Copy the magic bytes identifying the file in
  81231. var pos = 0;
  81232. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81233. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81234. }
  81235. // Add the json info
  81236. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81237. pos += infoBuffer.byteLength;
  81238. // Finally inserts the texture data
  81239. for (var i = 0; i <= mipmapsCount; i++) {
  81240. for (var face = 0; face < 6; face++) {
  81241. var dataBuffer = specularTextures[i * 6 + face];
  81242. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81243. pos += dataBuffer.byteLength;
  81244. }
  81245. }
  81246. // Voila
  81247. return finalBuffer;
  81248. });
  81249. };
  81250. /**
  81251. * Creates a JSON representation of the spherical data.
  81252. * @param texture defines the texture containing the polynomials
  81253. * @return the JSON representation of the spherical info
  81254. */
  81255. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81256. var polynmials = texture.sphericalPolynomial;
  81257. if (polynmials == null) {
  81258. return null;
  81259. }
  81260. return {
  81261. polynomials: true,
  81262. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81263. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81264. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81265. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81266. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81267. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81268. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81269. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81270. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81271. };
  81272. };
  81273. /**
  81274. * Uploads the texture info contained in the env file to te GPU.
  81275. * @param texture defines the internal texture to upload to
  81276. * @param arrayBuffer defines the buffer cotaining the data to load
  81277. * @param info defines the texture info retrieved through the GetEnvInfo method
  81278. * @returns a promise
  81279. */
  81280. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81281. if (info.version !== 1) {
  81282. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81283. }
  81284. var specularInfo = info.specular;
  81285. if (!specularInfo) {
  81286. // Nothing else parsed so far
  81287. return Promise.resolve();
  81288. }
  81289. // Double checks the enclosed info
  81290. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81291. mipmapsCount = Math.round(mipmapsCount) + 1;
  81292. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81293. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81294. }
  81295. // Gets everything ready.
  81296. var engine = texture.getEngine();
  81297. var expandTexture = false;
  81298. var generateNonLODTextures = false;
  81299. var rgbdPostProcess = null;
  81300. var cubeRtt = null;
  81301. var lodTextures = null;
  81302. var caps = engine.getCaps();
  81303. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81304. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81305. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81306. // Add extra process if texture lod is not supported
  81307. if (!caps.textureLOD) {
  81308. expandTexture = false;
  81309. generateNonLODTextures = true;
  81310. lodTextures = {};
  81311. }
  81312. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81313. else if (engine.webGLVersion < 2) {
  81314. expandTexture = false;
  81315. }
  81316. // If half float available we can uncompress the texture
  81317. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81318. expandTexture = true;
  81319. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81320. }
  81321. // If full float available we can uncompress the texture
  81322. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81323. expandTexture = true;
  81324. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81325. }
  81326. // Expand the texture if possible
  81327. if (expandTexture) {
  81328. // Simply run through the decode PP
  81329. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81330. texture._isRGBD = false;
  81331. texture.invertY = false;
  81332. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81333. generateDepthBuffer: false,
  81334. generateMipMaps: true,
  81335. generateStencilBuffer: false,
  81336. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81337. type: texture.type,
  81338. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81339. });
  81340. }
  81341. else {
  81342. texture._isRGBD = true;
  81343. texture.invertY = true;
  81344. // In case of missing support, applies the same patch than DDS files.
  81345. if (generateNonLODTextures) {
  81346. var mipSlices = 3;
  81347. var scale = texture._lodGenerationScale;
  81348. var offset = texture._lodGenerationOffset;
  81349. for (var i = 0; i < mipSlices; i++) {
  81350. //compute LOD from even spacing in smoothness (matching shader calculation)
  81351. var smoothness = i / (mipSlices - 1);
  81352. var roughness = 1 - smoothness;
  81353. var minLODIndex = offset; // roughness = 0
  81354. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81355. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81356. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81357. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81358. glTextureFromLod.isCube = true;
  81359. glTextureFromLod.invertY = true;
  81360. glTextureFromLod.generateMipMaps = false;
  81361. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81362. // Wrap in a base texture for easy binding.
  81363. var lodTexture = new BABYLON.BaseTexture(null);
  81364. lodTexture.isCube = true;
  81365. lodTexture._texture = glTextureFromLod;
  81366. lodTextures[mipmapIndex] = lodTexture;
  81367. switch (i) {
  81368. case 0:
  81369. texture._lodTextureLow = lodTexture;
  81370. break;
  81371. case 1:
  81372. texture._lodTextureMid = lodTexture;
  81373. break;
  81374. case 2:
  81375. texture._lodTextureHigh = lodTexture;
  81376. break;
  81377. }
  81378. }
  81379. }
  81380. }
  81381. var promises = [];
  81382. var _loop_3 = function (i) {
  81383. var _loop_4 = function (face) {
  81384. // Retrieves the face data
  81385. var imageData = specularInfo.mipmaps[i * 6 + face];
  81386. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81387. // Constructs an image element from bytes
  81388. var blob = new Blob([bytes], { type: 'image/png' });
  81389. var url = URL.createObjectURL(blob);
  81390. var image = new Image();
  81391. image.src = url;
  81392. // Enqueue promise to upload to the texture.
  81393. var promise = new Promise(function (resolve, reject) {
  81394. ;
  81395. image.onload = function () {
  81396. if (expandTexture) {
  81397. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81398. reject(message);
  81399. }, image);
  81400. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81401. // Uncompress the data to a RTT
  81402. rgbdPostProcess.onApply = function (effect) {
  81403. effect._bindTexture("textureSampler", tempTexture_1);
  81404. effect.setFloat2("scale", 1, 1);
  81405. };
  81406. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81407. // Cleanup
  81408. engine.restoreDefaultFramebuffer();
  81409. tempTexture_1.dispose();
  81410. window.URL.revokeObjectURL(url);
  81411. resolve();
  81412. });
  81413. }
  81414. else {
  81415. engine._uploadImageToTexture(texture, face, i, image);
  81416. // Upload the face to the none lod texture support
  81417. if (generateNonLODTextures) {
  81418. var lodTexture = lodTextures[i];
  81419. if (lodTexture) {
  81420. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81421. }
  81422. }
  81423. resolve();
  81424. }
  81425. };
  81426. image.onerror = function (error) {
  81427. reject(error);
  81428. };
  81429. });
  81430. promises.push(promise);
  81431. };
  81432. // All faces
  81433. for (var face = 0; face < 6; face++) {
  81434. _loop_4(face);
  81435. }
  81436. };
  81437. // All mipmaps
  81438. for (var i = 0; i < mipmapsCount; i++) {
  81439. _loop_3(i);
  81440. }
  81441. // Once all done, finishes the cleanup and return
  81442. return Promise.all(promises).then(function () {
  81443. // Relase temp RTT.
  81444. if (cubeRtt) {
  81445. engine._releaseFramebufferObjects(cubeRtt);
  81446. cubeRtt._swapAndDie(texture);
  81447. }
  81448. // Relase temp Post Process.
  81449. if (rgbdPostProcess) {
  81450. rgbdPostProcess.dispose();
  81451. }
  81452. // Flag internal texture as ready in case they are in use.
  81453. if (generateNonLODTextures) {
  81454. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81455. texture._lodTextureHigh._texture.isReady = true;
  81456. }
  81457. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81458. texture._lodTextureMid._texture.isReady = true;
  81459. }
  81460. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81461. texture._lodTextureLow._texture.isReady = true;
  81462. }
  81463. }
  81464. });
  81465. };
  81466. /**
  81467. * Uploads spherical polynomials information to the texture.
  81468. * @param texture defines the texture we are trying to upload the information to
  81469. * @param arrayBuffer defines the array buffer holding the data
  81470. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81471. */
  81472. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81473. if (info.version !== 1) {
  81474. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81475. }
  81476. var irradianceInfo = info.irradiance;
  81477. if (!irradianceInfo) {
  81478. return;
  81479. }
  81480. //harmonics now represent radiance
  81481. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81482. if (irradianceInfo.polynomials) {
  81483. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81484. }
  81485. else {
  81486. // convert From SH to SP.
  81487. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81488. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81489. }
  81490. };
  81491. /**
  81492. * Upload spherical polynomial coefficients to the texture
  81493. * @param polynmials Spherical polynmial coefficients (9)
  81494. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81495. */
  81496. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81497. outPolynomialCoefficents.x.x = polynmials.x[0];
  81498. outPolynomialCoefficents.x.y = polynmials.x[1];
  81499. outPolynomialCoefficents.x.z = polynmials.x[2];
  81500. outPolynomialCoefficents.y.x = polynmials.y[0];
  81501. outPolynomialCoefficents.y.y = polynmials.y[1];
  81502. outPolynomialCoefficents.y.z = polynmials.y[2];
  81503. outPolynomialCoefficents.z.x = polynmials.z[0];
  81504. outPolynomialCoefficents.z.y = polynmials.z[1];
  81505. outPolynomialCoefficents.z.z = polynmials.z[2];
  81506. //xx
  81507. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81508. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81509. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81510. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81511. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81512. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81513. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81514. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81515. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81516. //yz
  81517. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81518. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81519. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81520. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81521. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81522. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81523. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81524. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81525. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81526. };
  81527. /**
  81528. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81529. * L = (1/pi) * E * rho
  81530. *
  81531. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81532. * @param harmonics Spherical harmonic coefficients (9)
  81533. */
  81534. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81535. var scaleFactor = 1 / Math.PI;
  81536. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81537. // (The pixel shader must apply albedo after texture fetches, etc).
  81538. harmonics.l00[0] *= scaleFactor;
  81539. harmonics.l00[1] *= scaleFactor;
  81540. harmonics.l00[2] *= scaleFactor;
  81541. harmonics.l1_1[0] *= scaleFactor;
  81542. harmonics.l1_1[1] *= scaleFactor;
  81543. harmonics.l1_1[2] *= scaleFactor;
  81544. harmonics.l10[0] *= scaleFactor;
  81545. harmonics.l10[1] *= scaleFactor;
  81546. harmonics.l10[2] *= scaleFactor;
  81547. harmonics.l11[0] *= scaleFactor;
  81548. harmonics.l11[1] *= scaleFactor;
  81549. harmonics.l11[2] *= scaleFactor;
  81550. harmonics.l2_2[0] *= scaleFactor;
  81551. harmonics.l2_2[1] *= scaleFactor;
  81552. harmonics.l2_2[2] *= scaleFactor;
  81553. harmonics.l2_1[0] *= scaleFactor;
  81554. harmonics.l2_1[1] *= scaleFactor;
  81555. harmonics.l2_1[2] *= scaleFactor;
  81556. harmonics.l20[0] *= scaleFactor;
  81557. harmonics.l20[1] *= scaleFactor;
  81558. harmonics.l20[2] *= scaleFactor;
  81559. harmonics.l21[0] *= scaleFactor;
  81560. harmonics.l21[1] *= scaleFactor;
  81561. harmonics.l21[2] *= scaleFactor;
  81562. harmonics.l22[0] *= scaleFactor;
  81563. harmonics.l22[1] *= scaleFactor;
  81564. harmonics.l22[2] *= scaleFactor;
  81565. };
  81566. /**
  81567. * Convert spherical harmonics to spherical polynomial coefficients
  81568. * @param harmonics Spherical harmonic coefficients (9)
  81569. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81570. */
  81571. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81572. var rPi = 1 / Math.PI;
  81573. //x
  81574. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81575. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81576. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81577. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81578. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81579. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81580. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81581. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81582. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81583. //xx
  81584. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81585. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81586. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81587. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81588. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81589. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81590. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81591. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81592. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81593. //yz
  81594. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81595. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81596. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81597. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81598. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81599. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81600. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81601. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81602. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81603. };
  81604. /**
  81605. * Magic number identifying the env file.
  81606. */
  81607. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81608. return EnvironmentTextureTools;
  81609. }());
  81610. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81611. })(BABYLON || (BABYLON = {}));
  81612. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81613. var BABYLON;
  81614. (function (BABYLON) {
  81615. /**
  81616. * This represents a texture coming from an HDR input.
  81617. *
  81618. * The only supported format is currently panorama picture stored in RGBE format.
  81619. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81620. */
  81621. var HDRCubeTexture = /** @class */ (function (_super) {
  81622. __extends(HDRCubeTexture, _super);
  81623. /**
  81624. * Instantiates an HDRTexture from the following parameters.
  81625. *
  81626. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81627. * @param scene The scene the texture will be used in
  81628. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81629. * @param noMipmap Forces to not generate the mipmap if true
  81630. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81631. * @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)
  81632. * @param reserved Reserved flag for internal use.
  81633. */
  81634. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81635. if (noMipmap === void 0) { noMipmap = false; }
  81636. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81637. if (gammaSpace === void 0) { gammaSpace = false; }
  81638. if (reserved === void 0) { reserved = false; }
  81639. if (onLoad === void 0) { onLoad = null; }
  81640. if (onError === void 0) { onError = null; }
  81641. var _this = _super.call(this, scene) || this;
  81642. _this._generateHarmonics = true;
  81643. _this._onLoad = null;
  81644. _this._onError = null;
  81645. /**
  81646. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81647. */
  81648. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81649. _this._isBlocking = true;
  81650. _this._rotationY = 0;
  81651. /**
  81652. * Gets or sets the center of the bounding box associated with the cube texture
  81653. * It must define where the camera used to render the texture was set
  81654. */
  81655. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81656. if (!url) {
  81657. return _this;
  81658. }
  81659. _this.name = url;
  81660. _this.url = url;
  81661. _this.hasAlpha = false;
  81662. _this.isCube = true;
  81663. _this._textureMatrix = BABYLON.Matrix.Identity();
  81664. _this._onLoad = onLoad;
  81665. _this._onError = onError;
  81666. _this.gammaSpace = gammaSpace;
  81667. _this._noMipmap = noMipmap;
  81668. _this._size = size;
  81669. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81670. if (!_this._texture) {
  81671. if (!scene.useDelayedTextureLoading) {
  81672. _this.loadTexture();
  81673. }
  81674. else {
  81675. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81676. }
  81677. }
  81678. return _this;
  81679. }
  81680. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81681. /**
  81682. * Gets wether or not the texture is blocking during loading.
  81683. */
  81684. get: function () {
  81685. return this._isBlocking;
  81686. },
  81687. /**
  81688. * Sets wether or not the texture is blocking during loading.
  81689. */
  81690. set: function (value) {
  81691. this._isBlocking = value;
  81692. },
  81693. enumerable: true,
  81694. configurable: true
  81695. });
  81696. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81697. /**
  81698. * Gets texture matrix rotation angle around Y axis radians.
  81699. */
  81700. get: function () {
  81701. return this._rotationY;
  81702. },
  81703. /**
  81704. * Sets texture matrix rotation angle around Y axis in radians.
  81705. */
  81706. set: function (value) {
  81707. this._rotationY = value;
  81708. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81709. },
  81710. enumerable: true,
  81711. configurable: true
  81712. });
  81713. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81714. get: function () {
  81715. return this._boundingBoxSize;
  81716. },
  81717. /**
  81718. * Gets or sets the size of the bounding box associated with the cube texture
  81719. * When defined, the cubemap will switch to local mode
  81720. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81721. * @example https://www.babylonjs-playground.com/#RNASML
  81722. */
  81723. set: function (value) {
  81724. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81725. return;
  81726. }
  81727. this._boundingBoxSize = value;
  81728. var scene = this.getScene();
  81729. if (scene) {
  81730. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81731. }
  81732. },
  81733. enumerable: true,
  81734. configurable: true
  81735. });
  81736. /**
  81737. * Occurs when the file is raw .hdr file.
  81738. */
  81739. HDRCubeTexture.prototype.loadTexture = function () {
  81740. var _this = this;
  81741. var callback = function (buffer) {
  81742. _this.lodGenerationOffset = 0.0;
  81743. _this.lodGenerationScale = 0.8;
  81744. var scene = _this.getScene();
  81745. if (!scene) {
  81746. return null;
  81747. }
  81748. // Extract the raw linear data.
  81749. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81750. // Generate harmonics if needed.
  81751. if (_this._generateHarmonics) {
  81752. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81753. _this.sphericalPolynomial = sphericalPolynomial;
  81754. }
  81755. var results = [];
  81756. var byteArray = null;
  81757. // Push each faces.
  81758. for (var j = 0; j < 6; j++) {
  81759. // Create uintarray fallback.
  81760. if (!scene.getEngine().getCaps().textureFloat) {
  81761. // 3 channels of 1 bytes per pixel in bytes.
  81762. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81763. byteArray = new Uint8Array(byteBuffer);
  81764. }
  81765. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81766. // If special cases.
  81767. if (_this.gammaSpace || byteArray) {
  81768. for (var i = 0; i < _this._size * _this._size; i++) {
  81769. // Put in gamma space if requested.
  81770. if (_this.gammaSpace) {
  81771. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81772. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81773. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81774. }
  81775. // Convert to int texture for fallback.
  81776. if (byteArray) {
  81777. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81778. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81779. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81780. // May use luminance instead if the result is not accurate.
  81781. var max = Math.max(Math.max(r, g), b);
  81782. if (max > 255) {
  81783. var scale = 255 / max;
  81784. r *= scale;
  81785. g *= scale;
  81786. b *= scale;
  81787. }
  81788. byteArray[(i * 3) + 0] = r;
  81789. byteArray[(i * 3) + 1] = g;
  81790. byteArray[(i * 3) + 2] = b;
  81791. }
  81792. }
  81793. }
  81794. if (byteArray) {
  81795. results.push(byteArray);
  81796. }
  81797. else {
  81798. results.push(dataFace);
  81799. }
  81800. }
  81801. return results;
  81802. };
  81803. var scene = this.getScene();
  81804. if (scene) {
  81805. 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);
  81806. }
  81807. };
  81808. HDRCubeTexture.prototype.clone = function () {
  81809. var scene = this.getScene();
  81810. if (!scene) {
  81811. return this;
  81812. }
  81813. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81814. // Base texture
  81815. newTexture.level = this.level;
  81816. newTexture.wrapU = this.wrapU;
  81817. newTexture.wrapV = this.wrapV;
  81818. newTexture.coordinatesIndex = this.coordinatesIndex;
  81819. newTexture.coordinatesMode = this.coordinatesMode;
  81820. return newTexture;
  81821. };
  81822. // Methods
  81823. HDRCubeTexture.prototype.delayLoad = function () {
  81824. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81825. return;
  81826. }
  81827. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81828. this._texture = this._getFromCache(this.url, this._noMipmap);
  81829. if (!this._texture) {
  81830. this.loadTexture();
  81831. }
  81832. };
  81833. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81834. return this._textureMatrix;
  81835. };
  81836. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81837. this._textureMatrix = value;
  81838. };
  81839. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81840. var texture = null;
  81841. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81842. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81843. texture.name = parsedTexture.name;
  81844. texture.hasAlpha = parsedTexture.hasAlpha;
  81845. texture.level = parsedTexture.level;
  81846. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81847. texture.isBlocking = parsedTexture.isBlocking;
  81848. }
  81849. if (texture) {
  81850. if (parsedTexture.boundingBoxPosition) {
  81851. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81852. }
  81853. if (parsedTexture.boundingBoxSize) {
  81854. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81855. }
  81856. if (parsedTexture.rotationY) {
  81857. texture.rotationY = parsedTexture.rotationY;
  81858. }
  81859. }
  81860. return texture;
  81861. };
  81862. HDRCubeTexture.prototype.serialize = function () {
  81863. if (!this.name) {
  81864. return null;
  81865. }
  81866. var serializationObject = {};
  81867. serializationObject.name = this.name;
  81868. serializationObject.hasAlpha = this.hasAlpha;
  81869. serializationObject.isCube = true;
  81870. serializationObject.level = this.level;
  81871. serializationObject.size = this._size;
  81872. serializationObject.coordinatesMode = this.coordinatesMode;
  81873. serializationObject.useInGammaSpace = this.gammaSpace;
  81874. serializationObject.generateHarmonics = this._generateHarmonics;
  81875. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81876. serializationObject.noMipmap = this._noMipmap;
  81877. serializationObject.isBlocking = this._isBlocking;
  81878. serializationObject.rotationY = this._rotationY;
  81879. return serializationObject;
  81880. };
  81881. HDRCubeTexture._facesMapping = [
  81882. "right",
  81883. "left",
  81884. "up",
  81885. "down",
  81886. "front",
  81887. "back"
  81888. ];
  81889. return HDRCubeTexture;
  81890. }(BABYLON.BaseTexture));
  81891. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81892. })(BABYLON || (BABYLON = {}));
  81893. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81894. var BABYLON;
  81895. (function (BABYLON) {
  81896. var IndexedVector2 = /** @class */ (function (_super) {
  81897. __extends(IndexedVector2, _super);
  81898. function IndexedVector2(original, index) {
  81899. var _this = _super.call(this, original.x, original.y) || this;
  81900. _this.index = index;
  81901. return _this;
  81902. }
  81903. return IndexedVector2;
  81904. }(BABYLON.Vector2));
  81905. var PolygonPoints = /** @class */ (function () {
  81906. function PolygonPoints() {
  81907. this.elements = new Array();
  81908. }
  81909. PolygonPoints.prototype.add = function (originalPoints) {
  81910. var _this = this;
  81911. var result = new Array();
  81912. originalPoints.forEach(function (point) {
  81913. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81914. var newPoint = new IndexedVector2(point, _this.elements.length);
  81915. result.push(newPoint);
  81916. _this.elements.push(newPoint);
  81917. }
  81918. });
  81919. return result;
  81920. };
  81921. PolygonPoints.prototype.computeBounds = function () {
  81922. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81923. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81924. this.elements.forEach(function (point) {
  81925. // x
  81926. if (point.x < lmin.x) {
  81927. lmin.x = point.x;
  81928. }
  81929. else if (point.x > lmax.x) {
  81930. lmax.x = point.x;
  81931. }
  81932. // y
  81933. if (point.y < lmin.y) {
  81934. lmin.y = point.y;
  81935. }
  81936. else if (point.y > lmax.y) {
  81937. lmax.y = point.y;
  81938. }
  81939. });
  81940. return {
  81941. min: lmin,
  81942. max: lmax,
  81943. width: lmax.x - lmin.x,
  81944. height: lmax.y - lmin.y
  81945. };
  81946. };
  81947. return PolygonPoints;
  81948. }());
  81949. var Polygon = /** @class */ (function () {
  81950. function Polygon() {
  81951. }
  81952. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81953. return [
  81954. new BABYLON.Vector2(xmin, ymin),
  81955. new BABYLON.Vector2(xmax, ymin),
  81956. new BABYLON.Vector2(xmax, ymax),
  81957. new BABYLON.Vector2(xmin, ymax)
  81958. ];
  81959. };
  81960. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81961. if (cx === void 0) { cx = 0; }
  81962. if (cy === void 0) { cy = 0; }
  81963. if (numberOfSides === void 0) { numberOfSides = 32; }
  81964. var result = new Array();
  81965. var angle = 0;
  81966. var increment = (Math.PI * 2) / numberOfSides;
  81967. for (var i = 0; i < numberOfSides; i++) {
  81968. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81969. angle -= increment;
  81970. }
  81971. return result;
  81972. };
  81973. Polygon.Parse = function (input) {
  81974. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81975. var i, result = [];
  81976. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81977. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81978. }
  81979. return result;
  81980. };
  81981. Polygon.StartingAt = function (x, y) {
  81982. return BABYLON.Path2.StartingAt(x, y);
  81983. };
  81984. return Polygon;
  81985. }());
  81986. BABYLON.Polygon = Polygon;
  81987. var PolygonMeshBuilder = /** @class */ (function () {
  81988. function PolygonMeshBuilder(name, contours, scene) {
  81989. this._points = new PolygonPoints();
  81990. this._outlinepoints = new PolygonPoints();
  81991. this._holes = new Array();
  81992. this._epoints = new Array();
  81993. this._eholes = new Array();
  81994. this._name = name;
  81995. this._scene = scene;
  81996. var points;
  81997. if (contours instanceof BABYLON.Path2) {
  81998. points = contours.getPoints();
  81999. }
  82000. else {
  82001. points = contours;
  82002. }
  82003. this._addToepoint(points);
  82004. this._points.add(points);
  82005. this._outlinepoints.add(points);
  82006. if (typeof earcut === 'undefined') {
  82007. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82008. }
  82009. }
  82010. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82011. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82012. var p = points_1[_i];
  82013. this._epoints.push(p.x, p.y);
  82014. }
  82015. };
  82016. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82017. this._points.add(hole);
  82018. var holepoints = new PolygonPoints();
  82019. holepoints.add(hole);
  82020. this._holes.push(holepoints);
  82021. this._eholes.push(this._epoints.length / 2);
  82022. this._addToepoint(hole);
  82023. return this;
  82024. };
  82025. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82026. var _this = this;
  82027. if (updatable === void 0) { updatable = false; }
  82028. if (depth === void 0) { depth = 0; }
  82029. var result = new BABYLON.Mesh(this._name, this._scene);
  82030. var normals = new Array();
  82031. var positions = new Array();
  82032. var uvs = new Array();
  82033. var bounds = this._points.computeBounds();
  82034. this._points.elements.forEach(function (p) {
  82035. normals.push(0, 1.0, 0);
  82036. positions.push(p.x, 0, p.y);
  82037. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82038. });
  82039. var indices = new Array();
  82040. var res = earcut(this._epoints, this._eholes, 2);
  82041. for (var i = 0; i < res.length; i++) {
  82042. indices.push(res[i]);
  82043. }
  82044. if (depth > 0) {
  82045. var positionscount = (positions.length / 3); //get the current pointcount
  82046. this._points.elements.forEach(function (p) {
  82047. normals.push(0, -1.0, 0);
  82048. positions.push(p.x, -depth, p.y);
  82049. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82050. });
  82051. var totalCount = indices.length;
  82052. for (var i = 0; i < totalCount; i += 3) {
  82053. var i0 = indices[i + 0];
  82054. var i1 = indices[i + 1];
  82055. var i2 = indices[i + 2];
  82056. indices.push(i2 + positionscount);
  82057. indices.push(i1 + positionscount);
  82058. indices.push(i0 + positionscount);
  82059. }
  82060. //Add the sides
  82061. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82062. this._holes.forEach(function (hole) {
  82063. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82064. });
  82065. }
  82066. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82067. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82068. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82069. result.setIndices(indices);
  82070. return result;
  82071. };
  82072. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82073. var StartIndex = positions.length / 3;
  82074. var ulength = 0;
  82075. for (var i = 0; i < points.elements.length; i++) {
  82076. var p = points.elements[i];
  82077. var p1;
  82078. if ((i + 1) > points.elements.length - 1) {
  82079. p1 = points.elements[0];
  82080. }
  82081. else {
  82082. p1 = points.elements[i + 1];
  82083. }
  82084. positions.push(p.x, 0, p.y);
  82085. positions.push(p.x, -depth, p.y);
  82086. positions.push(p1.x, 0, p1.y);
  82087. positions.push(p1.x, -depth, p1.y);
  82088. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82089. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82090. var v3 = v2.subtract(v1);
  82091. var v4 = new BABYLON.Vector3(0, 1, 0);
  82092. var vn = BABYLON.Vector3.Cross(v3, v4);
  82093. vn = vn.normalize();
  82094. uvs.push(ulength / bounds.width, 0);
  82095. uvs.push(ulength / bounds.width, 1);
  82096. ulength += v3.length();
  82097. uvs.push((ulength / bounds.width), 0);
  82098. uvs.push((ulength / bounds.width), 1);
  82099. if (!flip) {
  82100. normals.push(-vn.x, -vn.y, -vn.z);
  82101. normals.push(-vn.x, -vn.y, -vn.z);
  82102. normals.push(-vn.x, -vn.y, -vn.z);
  82103. normals.push(-vn.x, -vn.y, -vn.z);
  82104. indices.push(StartIndex);
  82105. indices.push(StartIndex + 1);
  82106. indices.push(StartIndex + 2);
  82107. indices.push(StartIndex + 1);
  82108. indices.push(StartIndex + 3);
  82109. indices.push(StartIndex + 2);
  82110. }
  82111. else {
  82112. normals.push(vn.x, vn.y, vn.z);
  82113. normals.push(vn.x, vn.y, vn.z);
  82114. normals.push(vn.x, vn.y, vn.z);
  82115. normals.push(vn.x, vn.y, vn.z);
  82116. indices.push(StartIndex);
  82117. indices.push(StartIndex + 2);
  82118. indices.push(StartIndex + 1);
  82119. indices.push(StartIndex + 1);
  82120. indices.push(StartIndex + 2);
  82121. indices.push(StartIndex + 3);
  82122. }
  82123. StartIndex += 4;
  82124. }
  82125. ;
  82126. };
  82127. return PolygonMeshBuilder;
  82128. }());
  82129. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82130. })(BABYLON || (BABYLON = {}));
  82131. //# sourceMappingURL=babylon.polygonMesh.js.map
  82132. var BABYLON;
  82133. (function (BABYLON) {
  82134. // Unique ID when we import meshes from Babylon to CSG
  82135. var currentCSGMeshId = 0;
  82136. // # class Vertex
  82137. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82138. // one to provide additional features like texture coordinates and vertex
  82139. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82140. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82141. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82142. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82143. // is not used anywhere else.
  82144. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82145. var Vertex = /** @class */ (function () {
  82146. function Vertex(pos, normal, uv) {
  82147. this.pos = pos;
  82148. this.normal = normal;
  82149. this.uv = uv;
  82150. }
  82151. Vertex.prototype.clone = function () {
  82152. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82153. };
  82154. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82155. // orientation of a polygon is flipped.
  82156. Vertex.prototype.flip = function () {
  82157. this.normal = this.normal.scale(-1);
  82158. };
  82159. // Create a new vertex between this vertex and `other` by linearly
  82160. // interpolating all properties using a parameter of `t`. Subclasses should
  82161. // override this to interpolate additional properties.
  82162. Vertex.prototype.interpolate = function (other, t) {
  82163. 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));
  82164. };
  82165. return Vertex;
  82166. }());
  82167. // # class Plane
  82168. // Represents a plane in 3D space.
  82169. var Plane = /** @class */ (function () {
  82170. function Plane(normal, w) {
  82171. this.normal = normal;
  82172. this.w = w;
  82173. }
  82174. Plane.FromPoints = function (a, b, c) {
  82175. var v0 = c.subtract(a);
  82176. var v1 = b.subtract(a);
  82177. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82178. return null;
  82179. }
  82180. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82181. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82182. };
  82183. Plane.prototype.clone = function () {
  82184. return new Plane(this.normal.clone(), this.w);
  82185. };
  82186. Plane.prototype.flip = function () {
  82187. this.normal.scaleInPlace(-1);
  82188. this.w = -this.w;
  82189. };
  82190. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82191. // fragments in the appropriate lists. Coplanar polygons go into either
  82192. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82193. // respect to this plane. Polygons in front or in back of this plane go into
  82194. // either `front` or `back`.
  82195. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82196. var COPLANAR = 0;
  82197. var FRONT = 1;
  82198. var BACK = 2;
  82199. var SPANNING = 3;
  82200. // Classify each point as well as the entire polygon into one of the above
  82201. // four classes.
  82202. var polygonType = 0;
  82203. var types = [];
  82204. var i;
  82205. var t;
  82206. for (i = 0; i < polygon.vertices.length; i++) {
  82207. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82208. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82209. polygonType |= type;
  82210. types.push(type);
  82211. }
  82212. // Put the polygon in the correct list, splitting it when necessary.
  82213. switch (polygonType) {
  82214. case COPLANAR:
  82215. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82216. break;
  82217. case FRONT:
  82218. front.push(polygon);
  82219. break;
  82220. case BACK:
  82221. back.push(polygon);
  82222. break;
  82223. case SPANNING:
  82224. var f = [], b = [];
  82225. for (i = 0; i < polygon.vertices.length; i++) {
  82226. var j = (i + 1) % polygon.vertices.length;
  82227. var ti = types[i], tj = types[j];
  82228. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82229. if (ti !== BACK)
  82230. f.push(vi);
  82231. if (ti !== FRONT)
  82232. b.push(ti !== BACK ? vi.clone() : vi);
  82233. if ((ti | tj) === SPANNING) {
  82234. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82235. var v = vi.interpolate(vj, t);
  82236. f.push(v);
  82237. b.push(v.clone());
  82238. }
  82239. }
  82240. var poly;
  82241. if (f.length >= 3) {
  82242. poly = new Polygon(f, polygon.shared);
  82243. if (poly.plane)
  82244. front.push(poly);
  82245. }
  82246. if (b.length >= 3) {
  82247. poly = new Polygon(b, polygon.shared);
  82248. if (poly.plane)
  82249. back.push(poly);
  82250. }
  82251. break;
  82252. }
  82253. };
  82254. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82255. // point is on the plane.
  82256. Plane.EPSILON = 1e-5;
  82257. return Plane;
  82258. }());
  82259. // # class Polygon
  82260. // Represents a convex polygon. The vertices used to initialize a polygon must
  82261. // be coplanar and form a convex loop.
  82262. //
  82263. // Each convex polygon has a `shared` property, which is shared between all
  82264. // polygons that are clones of each other or were split from the same polygon.
  82265. // This can be used to define per-polygon properties (such as surface color).
  82266. var Polygon = /** @class */ (function () {
  82267. function Polygon(vertices, shared) {
  82268. this.vertices = vertices;
  82269. this.shared = shared;
  82270. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82271. }
  82272. Polygon.prototype.clone = function () {
  82273. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82274. return new Polygon(vertices, this.shared);
  82275. };
  82276. Polygon.prototype.flip = function () {
  82277. this.vertices.reverse().map(function (v) { v.flip(); });
  82278. this.plane.flip();
  82279. };
  82280. return Polygon;
  82281. }());
  82282. // # class Node
  82283. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82284. // by picking a polygon to split along. That polygon (and all other coplanar
  82285. // polygons) are added directly to that node and the other polygons are added to
  82286. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82287. // no distinction between internal and leaf nodes.
  82288. var Node = /** @class */ (function () {
  82289. function Node(polygons) {
  82290. this.plane = null;
  82291. this.front = null;
  82292. this.back = null;
  82293. this.polygons = new Array();
  82294. if (polygons) {
  82295. this.build(polygons);
  82296. }
  82297. }
  82298. Node.prototype.clone = function () {
  82299. var node = new Node();
  82300. node.plane = this.plane && this.plane.clone();
  82301. node.front = this.front && this.front.clone();
  82302. node.back = this.back && this.back.clone();
  82303. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82304. return node;
  82305. };
  82306. // Convert solid space to empty space and empty space to solid space.
  82307. Node.prototype.invert = function () {
  82308. for (var i = 0; i < this.polygons.length; i++) {
  82309. this.polygons[i].flip();
  82310. }
  82311. if (this.plane) {
  82312. this.plane.flip();
  82313. }
  82314. if (this.front) {
  82315. this.front.invert();
  82316. }
  82317. if (this.back) {
  82318. this.back.invert();
  82319. }
  82320. var temp = this.front;
  82321. this.front = this.back;
  82322. this.back = temp;
  82323. };
  82324. // Recursively remove all polygons in `polygons` that are inside this BSP
  82325. // tree.
  82326. Node.prototype.clipPolygons = function (polygons) {
  82327. if (!this.plane)
  82328. return polygons.slice();
  82329. var front = new Array(), back = new Array();
  82330. for (var i = 0; i < polygons.length; i++) {
  82331. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82332. }
  82333. if (this.front) {
  82334. front = this.front.clipPolygons(front);
  82335. }
  82336. if (this.back) {
  82337. back = this.back.clipPolygons(back);
  82338. }
  82339. else {
  82340. back = [];
  82341. }
  82342. return front.concat(back);
  82343. };
  82344. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82345. // `bsp`.
  82346. Node.prototype.clipTo = function (bsp) {
  82347. this.polygons = bsp.clipPolygons(this.polygons);
  82348. if (this.front)
  82349. this.front.clipTo(bsp);
  82350. if (this.back)
  82351. this.back.clipTo(bsp);
  82352. };
  82353. // Return a list of all polygons in this BSP tree.
  82354. Node.prototype.allPolygons = function () {
  82355. var polygons = this.polygons.slice();
  82356. if (this.front)
  82357. polygons = polygons.concat(this.front.allPolygons());
  82358. if (this.back)
  82359. polygons = polygons.concat(this.back.allPolygons());
  82360. return polygons;
  82361. };
  82362. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82363. // new polygons are filtered down to the bottom of the tree and become new
  82364. // nodes there. Each set of polygons is partitioned using the first polygon
  82365. // (no heuristic is used to pick a good split).
  82366. Node.prototype.build = function (polygons) {
  82367. if (!polygons.length)
  82368. return;
  82369. if (!this.plane)
  82370. this.plane = polygons[0].plane.clone();
  82371. var front = new Array(), back = new Array();
  82372. for (var i = 0; i < polygons.length; i++) {
  82373. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82374. }
  82375. if (front.length) {
  82376. if (!this.front)
  82377. this.front = new Node();
  82378. this.front.build(front);
  82379. }
  82380. if (back.length) {
  82381. if (!this.back)
  82382. this.back = new Node();
  82383. this.back.build(back);
  82384. }
  82385. };
  82386. return Node;
  82387. }());
  82388. var CSG = /** @class */ (function () {
  82389. function CSG() {
  82390. this.polygons = new Array();
  82391. }
  82392. // Convert BABYLON.Mesh to BABYLON.CSG
  82393. CSG.FromMesh = function (mesh) {
  82394. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82395. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82396. if (mesh instanceof BABYLON.Mesh) {
  82397. mesh.computeWorldMatrix(true);
  82398. matrix = mesh.getWorldMatrix();
  82399. meshPosition = mesh.position.clone();
  82400. meshRotation = mesh.rotation.clone();
  82401. if (mesh.rotationQuaternion) {
  82402. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82403. }
  82404. meshScaling = mesh.scaling.clone();
  82405. }
  82406. else {
  82407. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82408. }
  82409. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82410. var subMeshes = mesh.subMeshes;
  82411. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82412. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82413. vertices = [];
  82414. for (var j = 0; j < 3; j++) {
  82415. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82416. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82417. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82418. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82419. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82420. vertex = new Vertex(position, normal, uv);
  82421. vertices.push(vertex);
  82422. }
  82423. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82424. // To handle the case of degenerated triangle
  82425. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82426. if (polygon.plane)
  82427. polygons.push(polygon);
  82428. }
  82429. }
  82430. var csg = CSG.FromPolygons(polygons);
  82431. csg.matrix = matrix;
  82432. csg.position = meshPosition;
  82433. csg.rotation = meshRotation;
  82434. csg.scaling = meshScaling;
  82435. csg.rotationQuaternion = meshRotationQuaternion;
  82436. currentCSGMeshId++;
  82437. return csg;
  82438. };
  82439. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82440. CSG.FromPolygons = function (polygons) {
  82441. var csg = new CSG();
  82442. csg.polygons = polygons;
  82443. return csg;
  82444. };
  82445. CSG.prototype.clone = function () {
  82446. var csg = new CSG();
  82447. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82448. csg.copyTransformAttributes(this);
  82449. return csg;
  82450. };
  82451. CSG.prototype.union = function (csg) {
  82452. var a = new Node(this.clone().polygons);
  82453. var b = new Node(csg.clone().polygons);
  82454. a.clipTo(b);
  82455. b.clipTo(a);
  82456. b.invert();
  82457. b.clipTo(a);
  82458. b.invert();
  82459. a.build(b.allPolygons());
  82460. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82461. };
  82462. CSG.prototype.unionInPlace = function (csg) {
  82463. var a = new Node(this.polygons);
  82464. var b = new Node(csg.polygons);
  82465. a.clipTo(b);
  82466. b.clipTo(a);
  82467. b.invert();
  82468. b.clipTo(a);
  82469. b.invert();
  82470. a.build(b.allPolygons());
  82471. this.polygons = a.allPolygons();
  82472. };
  82473. CSG.prototype.subtract = function (csg) {
  82474. var a = new Node(this.clone().polygons);
  82475. var b = new Node(csg.clone().polygons);
  82476. a.invert();
  82477. a.clipTo(b);
  82478. b.clipTo(a);
  82479. b.invert();
  82480. b.clipTo(a);
  82481. b.invert();
  82482. a.build(b.allPolygons());
  82483. a.invert();
  82484. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82485. };
  82486. CSG.prototype.subtractInPlace = function (csg) {
  82487. var a = new Node(this.polygons);
  82488. var b = new Node(csg.polygons);
  82489. a.invert();
  82490. a.clipTo(b);
  82491. b.clipTo(a);
  82492. b.invert();
  82493. b.clipTo(a);
  82494. b.invert();
  82495. a.build(b.allPolygons());
  82496. a.invert();
  82497. this.polygons = a.allPolygons();
  82498. };
  82499. CSG.prototype.intersect = function (csg) {
  82500. var a = new Node(this.clone().polygons);
  82501. var b = new Node(csg.clone().polygons);
  82502. a.invert();
  82503. b.clipTo(a);
  82504. b.invert();
  82505. a.clipTo(b);
  82506. b.clipTo(a);
  82507. a.build(b.allPolygons());
  82508. a.invert();
  82509. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82510. };
  82511. CSG.prototype.intersectInPlace = function (csg) {
  82512. var a = new Node(this.polygons);
  82513. var b = new Node(csg.polygons);
  82514. a.invert();
  82515. b.clipTo(a);
  82516. b.invert();
  82517. a.clipTo(b);
  82518. b.clipTo(a);
  82519. a.build(b.allPolygons());
  82520. a.invert();
  82521. this.polygons = a.allPolygons();
  82522. };
  82523. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82524. // not modified.
  82525. CSG.prototype.inverse = function () {
  82526. var csg = this.clone();
  82527. csg.inverseInPlace();
  82528. return csg;
  82529. };
  82530. CSG.prototype.inverseInPlace = function () {
  82531. this.polygons.map(function (p) { p.flip(); });
  82532. };
  82533. // This is used to keep meshes transformations so they can be restored
  82534. // when we build back a Babylon Mesh
  82535. // NB : All CSG operations are performed in world coordinates
  82536. CSG.prototype.copyTransformAttributes = function (csg) {
  82537. this.matrix = csg.matrix;
  82538. this.position = csg.position;
  82539. this.rotation = csg.rotation;
  82540. this.scaling = csg.scaling;
  82541. this.rotationQuaternion = csg.rotationQuaternion;
  82542. return this;
  82543. };
  82544. // Build Raw mesh from CSG
  82545. // Coordinates here are in world space
  82546. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82547. var matrix = this.matrix.clone();
  82548. matrix.invert();
  82549. 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;
  82550. if (keepSubMeshes) {
  82551. // Sort Polygons, since subMeshes are indices range
  82552. polygons.sort(function (a, b) {
  82553. if (a.shared.meshId === b.shared.meshId) {
  82554. return a.shared.subMeshId - b.shared.subMeshId;
  82555. }
  82556. else {
  82557. return a.shared.meshId - b.shared.meshId;
  82558. }
  82559. });
  82560. }
  82561. for (var i = 0, il = polygons.length; i < il; i++) {
  82562. polygon = polygons[i];
  82563. // Building SubMeshes
  82564. if (!subMesh_dict[polygon.shared.meshId]) {
  82565. subMesh_dict[polygon.shared.meshId] = {};
  82566. }
  82567. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82568. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82569. indexStart: +Infinity,
  82570. indexEnd: -Infinity,
  82571. materialIndex: polygon.shared.materialIndex
  82572. };
  82573. }
  82574. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82575. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82576. polygonIndices[0] = 0;
  82577. polygonIndices[1] = j - 1;
  82578. polygonIndices[2] = j;
  82579. for (var k = 0; k < 3; k++) {
  82580. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82581. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82582. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82583. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82584. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82585. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82586. // Check if 2 points can be merged
  82587. if (!(typeof vertex_idx !== 'undefined' &&
  82588. normals[vertex_idx * 3] === localNormal.x &&
  82589. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82590. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82591. uvs[vertex_idx * 2] === uv.x &&
  82592. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82593. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82594. uvs.push(uv.x, uv.y);
  82595. normals.push(normal.x, normal.y, normal.z);
  82596. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82597. }
  82598. indices.push(vertex_idx);
  82599. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82600. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82601. currentIndex++;
  82602. }
  82603. }
  82604. }
  82605. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82606. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82607. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82608. mesh.setIndices(indices, null);
  82609. if (keepSubMeshes) {
  82610. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82611. var materialIndexOffset = 0, materialMaxIndex;
  82612. mesh.subMeshes = new Array();
  82613. for (var m in subMesh_dict) {
  82614. materialMaxIndex = -1;
  82615. for (var sm in subMesh_dict[m]) {
  82616. subMesh_obj = subMesh_dict[m][sm];
  82617. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82618. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82619. }
  82620. materialIndexOffset += ++materialMaxIndex;
  82621. }
  82622. }
  82623. return mesh;
  82624. };
  82625. // Build Mesh from CSG taking material and transforms into account
  82626. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82627. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82628. mesh.material = material;
  82629. mesh.position.copyFrom(this.position);
  82630. mesh.rotation.copyFrom(this.rotation);
  82631. if (this.rotationQuaternion) {
  82632. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82633. }
  82634. mesh.scaling.copyFrom(this.scaling);
  82635. mesh.computeWorldMatrix(true);
  82636. return mesh;
  82637. };
  82638. return CSG;
  82639. }());
  82640. BABYLON.CSG = CSG;
  82641. })(BABYLON || (BABYLON = {}));
  82642. //# sourceMappingURL=babylon.csg.js.map
  82643. var BABYLON;
  82644. (function (BABYLON) {
  82645. var LensFlare = /** @class */ (function () {
  82646. function LensFlare(size, position, color, imgUrl, system) {
  82647. this.size = size;
  82648. this.position = position;
  82649. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82650. this.color = color || new BABYLON.Color3(1, 1, 1);
  82651. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82652. this._system = system;
  82653. system.lensFlares.push(this);
  82654. }
  82655. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82656. return new LensFlare(size, position, color, imgUrl, system);
  82657. };
  82658. LensFlare.prototype.dispose = function () {
  82659. if (this.texture) {
  82660. this.texture.dispose();
  82661. }
  82662. // Remove from scene
  82663. var index = this._system.lensFlares.indexOf(this);
  82664. this._system.lensFlares.splice(index, 1);
  82665. };
  82666. ;
  82667. return LensFlare;
  82668. }());
  82669. BABYLON.LensFlare = LensFlare;
  82670. })(BABYLON || (BABYLON = {}));
  82671. //# sourceMappingURL=babylon.lensFlare.js.map
  82672. var BABYLON;
  82673. (function (BABYLON) {
  82674. var LensFlareSystem = /** @class */ (function () {
  82675. function LensFlareSystem(name, emitter, scene) {
  82676. this.name = name;
  82677. this.lensFlares = new Array();
  82678. this.borderLimit = 300;
  82679. this.viewportBorder = 0;
  82680. this.layerMask = 0x0FFFFFFF;
  82681. this._vertexBuffers = {};
  82682. this._isEnabled = true;
  82683. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82684. this._emitter = emitter;
  82685. this.id = name;
  82686. scene.lensFlareSystems.push(this);
  82687. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82688. var engine = scene.getEngine();
  82689. // VBO
  82690. var vertices = [];
  82691. vertices.push(1, 1);
  82692. vertices.push(-1, 1);
  82693. vertices.push(-1, -1);
  82694. vertices.push(1, -1);
  82695. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82696. // Indices
  82697. var indices = [];
  82698. indices.push(0);
  82699. indices.push(1);
  82700. indices.push(2);
  82701. indices.push(0);
  82702. indices.push(2);
  82703. indices.push(3);
  82704. this._indexBuffer = engine.createIndexBuffer(indices);
  82705. // Effects
  82706. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82707. }
  82708. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82709. get: function () {
  82710. return this._isEnabled;
  82711. },
  82712. set: function (value) {
  82713. this._isEnabled = value;
  82714. },
  82715. enumerable: true,
  82716. configurable: true
  82717. });
  82718. LensFlareSystem.prototype.getScene = function () {
  82719. return this._scene;
  82720. };
  82721. LensFlareSystem.prototype.getEmitter = function () {
  82722. return this._emitter;
  82723. };
  82724. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82725. this._emitter = newEmitter;
  82726. };
  82727. LensFlareSystem.prototype.getEmitterPosition = function () {
  82728. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82729. };
  82730. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82731. var position = this.getEmitterPosition();
  82732. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82733. this._positionX = position.x;
  82734. this._positionY = position.y;
  82735. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82736. if (this.viewportBorder > 0) {
  82737. globalViewport.x -= this.viewportBorder;
  82738. globalViewport.y -= this.viewportBorder;
  82739. globalViewport.width += this.viewportBorder * 2;
  82740. globalViewport.height += this.viewportBorder * 2;
  82741. position.x += this.viewportBorder;
  82742. position.y += this.viewportBorder;
  82743. this._positionX += this.viewportBorder;
  82744. this._positionY += this.viewportBorder;
  82745. }
  82746. if (position.z > 0) {
  82747. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82748. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82749. return true;
  82750. }
  82751. return true;
  82752. }
  82753. return false;
  82754. };
  82755. LensFlareSystem.prototype._isVisible = function () {
  82756. if (!this._isEnabled || !this._scene.activeCamera) {
  82757. return false;
  82758. }
  82759. var emitterPosition = this.getEmitterPosition();
  82760. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82761. var distance = direction.length();
  82762. direction.normalize();
  82763. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82764. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82765. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82766. };
  82767. LensFlareSystem.prototype.render = function () {
  82768. if (!this._effect.isReady() || !this._scene.activeCamera)
  82769. return false;
  82770. var engine = this._scene.getEngine();
  82771. var viewport = this._scene.activeCamera.viewport;
  82772. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82773. // Position
  82774. if (!this.computeEffectivePosition(globalViewport)) {
  82775. return false;
  82776. }
  82777. // Visibility
  82778. if (!this._isVisible()) {
  82779. return false;
  82780. }
  82781. // Intensity
  82782. var awayX;
  82783. var awayY;
  82784. if (this._positionX < this.borderLimit + globalViewport.x) {
  82785. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82786. }
  82787. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82788. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82789. }
  82790. else {
  82791. awayX = 0;
  82792. }
  82793. if (this._positionY < this.borderLimit + globalViewport.y) {
  82794. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82795. }
  82796. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82797. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82798. }
  82799. else {
  82800. awayY = 0;
  82801. }
  82802. var away = (awayX > awayY) ? awayX : awayY;
  82803. away -= this.viewportBorder;
  82804. if (away > this.borderLimit) {
  82805. away = this.borderLimit;
  82806. }
  82807. var intensity = 1.0 - (away / this.borderLimit);
  82808. if (intensity < 0) {
  82809. return false;
  82810. }
  82811. if (intensity > 1.0) {
  82812. intensity = 1.0;
  82813. }
  82814. if (this.viewportBorder > 0) {
  82815. globalViewport.x += this.viewportBorder;
  82816. globalViewport.y += this.viewportBorder;
  82817. globalViewport.width -= this.viewportBorder * 2;
  82818. globalViewport.height -= this.viewportBorder * 2;
  82819. this._positionX -= this.viewportBorder;
  82820. this._positionY -= this.viewportBorder;
  82821. }
  82822. // Position
  82823. var centerX = globalViewport.x + globalViewport.width / 2;
  82824. var centerY = globalViewport.y + globalViewport.height / 2;
  82825. var distX = centerX - this._positionX;
  82826. var distY = centerY - this._positionY;
  82827. // Effects
  82828. engine.enableEffect(this._effect);
  82829. engine.setState(false);
  82830. engine.setDepthBuffer(false);
  82831. // VBOs
  82832. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82833. // Flares
  82834. for (var index = 0; index < this.lensFlares.length; index++) {
  82835. var flare = this.lensFlares[index];
  82836. engine.setAlphaMode(flare.alphaMode);
  82837. var x = centerX - (distX * flare.position);
  82838. var y = centerY - (distY * flare.position);
  82839. var cw = flare.size;
  82840. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82841. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82842. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82843. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82844. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82845. // Texture
  82846. this._effect.setTexture("textureSampler", flare.texture);
  82847. // Color
  82848. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82849. // Draw order
  82850. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82851. }
  82852. engine.setDepthBuffer(true);
  82853. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82854. return true;
  82855. };
  82856. LensFlareSystem.prototype.dispose = function () {
  82857. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82858. if (vertexBuffer) {
  82859. vertexBuffer.dispose();
  82860. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82861. }
  82862. if (this._indexBuffer) {
  82863. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82864. this._indexBuffer = null;
  82865. }
  82866. while (this.lensFlares.length) {
  82867. this.lensFlares[0].dispose();
  82868. }
  82869. // Remove from scene
  82870. var index = this._scene.lensFlareSystems.indexOf(this);
  82871. this._scene.lensFlareSystems.splice(index, 1);
  82872. };
  82873. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82874. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82875. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82876. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82877. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82878. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82879. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82880. var parsedFlare = parsedLensFlareSystem.flares[index];
  82881. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82882. }
  82883. return lensFlareSystem;
  82884. };
  82885. LensFlareSystem.prototype.serialize = function () {
  82886. var serializationObject = {};
  82887. serializationObject.id = this.id;
  82888. serializationObject.name = this.name;
  82889. serializationObject.emitterId = this.getEmitter().id;
  82890. serializationObject.borderLimit = this.borderLimit;
  82891. serializationObject.flares = [];
  82892. for (var index = 0; index < this.lensFlares.length; index++) {
  82893. var flare = this.lensFlares[index];
  82894. serializationObject.flares.push({
  82895. size: flare.size,
  82896. position: flare.position,
  82897. color: flare.color.asArray(),
  82898. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82899. });
  82900. }
  82901. return serializationObject;
  82902. };
  82903. return LensFlareSystem;
  82904. }());
  82905. BABYLON.LensFlareSystem = LensFlareSystem;
  82906. })(BABYLON || (BABYLON = {}));
  82907. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82908. var BABYLON;
  82909. (function (BABYLON) {
  82910. /**
  82911. * This is a holder class for the physics joint created by the physics plugin.
  82912. * It holds a set of functions to control the underlying joint.
  82913. */
  82914. var PhysicsJoint = /** @class */ (function () {
  82915. function PhysicsJoint(type, jointData) {
  82916. this.type = type;
  82917. this.jointData = jointData;
  82918. jointData.nativeParams = jointData.nativeParams || {};
  82919. }
  82920. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82921. get: function () {
  82922. return this._physicsJoint;
  82923. },
  82924. set: function (newJoint) {
  82925. if (this._physicsJoint) {
  82926. //remove from the wolrd
  82927. }
  82928. this._physicsJoint = newJoint;
  82929. },
  82930. enumerable: true,
  82931. configurable: true
  82932. });
  82933. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82934. set: function (physicsPlugin) {
  82935. this._physicsPlugin = physicsPlugin;
  82936. },
  82937. enumerable: true,
  82938. configurable: true
  82939. });
  82940. /**
  82941. * Execute a function that is physics-plugin specific.
  82942. * @param {Function} func the function that will be executed.
  82943. * It accepts two parameters: the physics world and the physics joint.
  82944. */
  82945. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82946. func(this._physicsPlugin.world, this._physicsJoint);
  82947. };
  82948. //TODO check if the native joints are the same
  82949. //Joint Types
  82950. PhysicsJoint.DistanceJoint = 0;
  82951. PhysicsJoint.HingeJoint = 1;
  82952. PhysicsJoint.BallAndSocketJoint = 2;
  82953. PhysicsJoint.WheelJoint = 3;
  82954. PhysicsJoint.SliderJoint = 4;
  82955. //OIMO
  82956. PhysicsJoint.PrismaticJoint = 5;
  82957. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82958. PhysicsJoint.UniversalJoint = 6;
  82959. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82960. //Cannon
  82961. //Similar to a Ball-Joint. Different in params
  82962. PhysicsJoint.PointToPointJoint = 8;
  82963. //Cannon only at the moment
  82964. PhysicsJoint.SpringJoint = 9;
  82965. PhysicsJoint.LockJoint = 10;
  82966. return PhysicsJoint;
  82967. }());
  82968. BABYLON.PhysicsJoint = PhysicsJoint;
  82969. /**
  82970. * A class representing a physics distance joint.
  82971. */
  82972. var DistanceJoint = /** @class */ (function (_super) {
  82973. __extends(DistanceJoint, _super);
  82974. function DistanceJoint(jointData) {
  82975. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82976. }
  82977. /**
  82978. * Update the predefined distance.
  82979. */
  82980. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82981. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82982. };
  82983. return DistanceJoint;
  82984. }(PhysicsJoint));
  82985. BABYLON.DistanceJoint = DistanceJoint;
  82986. var MotorEnabledJoint = /** @class */ (function (_super) {
  82987. __extends(MotorEnabledJoint, _super);
  82988. function MotorEnabledJoint(type, jointData) {
  82989. return _super.call(this, type, jointData) || this;
  82990. }
  82991. /**
  82992. * Set the motor values.
  82993. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82994. * @param {number} force the force to apply
  82995. * @param {number} maxForce max force for this motor.
  82996. */
  82997. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82998. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82999. };
  83000. /**
  83001. * Set the motor's limits.
  83002. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83003. */
  83004. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83005. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83006. };
  83007. return MotorEnabledJoint;
  83008. }(PhysicsJoint));
  83009. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83010. /**
  83011. * This class represents a single hinge physics joint
  83012. */
  83013. var HingeJoint = /** @class */ (function (_super) {
  83014. __extends(HingeJoint, _super);
  83015. function HingeJoint(jointData) {
  83016. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83017. }
  83018. /**
  83019. * Set the motor values.
  83020. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83021. * @param {number} force the force to apply
  83022. * @param {number} maxForce max force for this motor.
  83023. */
  83024. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83025. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83026. };
  83027. /**
  83028. * Set the motor's limits.
  83029. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83030. */
  83031. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83032. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83033. };
  83034. return HingeJoint;
  83035. }(MotorEnabledJoint));
  83036. BABYLON.HingeJoint = HingeJoint;
  83037. /**
  83038. * This class represents a dual hinge physics joint (same as wheel joint)
  83039. */
  83040. var Hinge2Joint = /** @class */ (function (_super) {
  83041. __extends(Hinge2Joint, _super);
  83042. function Hinge2Joint(jointData) {
  83043. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83044. }
  83045. /**
  83046. * Set the motor values.
  83047. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83048. * @param {number} force the force to apply
  83049. * @param {number} maxForce max force for this motor.
  83050. * @param {motorIndex} the motor's index, 0 or 1.
  83051. */
  83052. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83053. if (motorIndex === void 0) { motorIndex = 0; }
  83054. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83055. };
  83056. /**
  83057. * Set the motor limits.
  83058. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83059. * @param {number} upperLimit the upper limit
  83060. * @param {number} lowerLimit lower limit
  83061. * @param {motorIndex} the motor's index, 0 or 1.
  83062. */
  83063. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83064. if (motorIndex === void 0) { motorIndex = 0; }
  83065. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83066. };
  83067. return Hinge2Joint;
  83068. }(MotorEnabledJoint));
  83069. BABYLON.Hinge2Joint = Hinge2Joint;
  83070. })(BABYLON || (BABYLON = {}));
  83071. //# sourceMappingURL=babylon.physicsJoint.js.map
  83072. var BABYLON;
  83073. (function (BABYLON) {
  83074. var PhysicsImpostor = /** @class */ (function () {
  83075. function PhysicsImpostor(object, type, _options, _scene) {
  83076. if (_options === void 0) { _options = { mass: 0 }; }
  83077. var _this = this;
  83078. this.object = object;
  83079. this.type = type;
  83080. this._options = _options;
  83081. this._scene = _scene;
  83082. this._bodyUpdateRequired = false;
  83083. this._onBeforePhysicsStepCallbacks = new Array();
  83084. this._onAfterPhysicsStepCallbacks = new Array();
  83085. this._onPhysicsCollideCallbacks = [];
  83086. this._deltaPosition = BABYLON.Vector3.Zero();
  83087. this._isDisposed = false;
  83088. //temp variables for parent rotation calculations
  83089. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83090. this._tmpQuat = new BABYLON.Quaternion();
  83091. this._tmpQuat2 = new BABYLON.Quaternion();
  83092. /**
  83093. * this function is executed by the physics engine.
  83094. */
  83095. this.beforeStep = function () {
  83096. if (!_this._physicsEngine) {
  83097. return;
  83098. }
  83099. _this.object.translate(_this._deltaPosition, -1);
  83100. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83101. _this.object.computeWorldMatrix(false);
  83102. if (_this.object.parent && _this.object.rotationQuaternion) {
  83103. _this.getParentsRotation();
  83104. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83105. }
  83106. else {
  83107. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83108. }
  83109. if (!_this._options.disableBidirectionalTransformation) {
  83110. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83111. }
  83112. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83113. func(_this);
  83114. });
  83115. };
  83116. /**
  83117. * this function is executed by the physics engine.
  83118. */
  83119. this.afterStep = function () {
  83120. if (!_this._physicsEngine) {
  83121. return;
  83122. }
  83123. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83124. func(_this);
  83125. });
  83126. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83127. // object has now its world rotation. needs to be converted to local.
  83128. if (_this.object.parent && _this.object.rotationQuaternion) {
  83129. _this.getParentsRotation();
  83130. _this._tmpQuat.conjugateInPlace();
  83131. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83132. }
  83133. // take the position set and make it the absolute position of this object.
  83134. _this.object.setAbsolutePosition(_this.object.position);
  83135. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83136. _this.object.translate(_this._deltaPosition, 1);
  83137. };
  83138. /**
  83139. * Legacy collision detection event support
  83140. */
  83141. this.onCollideEvent = null;
  83142. //event and body object due to cannon's event-based architecture.
  83143. this.onCollide = function (e) {
  83144. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83145. return;
  83146. }
  83147. if (!_this._physicsEngine) {
  83148. return;
  83149. }
  83150. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83151. if (otherImpostor) {
  83152. // Legacy collision detection event support
  83153. if (_this.onCollideEvent) {
  83154. _this.onCollideEvent(_this, otherImpostor);
  83155. }
  83156. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83157. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83158. }).forEach(function (obj) {
  83159. obj.callback(_this, otherImpostor);
  83160. });
  83161. }
  83162. };
  83163. //sanity check!
  83164. if (!this.object) {
  83165. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83166. return;
  83167. }
  83168. //legacy support for old syntax.
  83169. if (!this._scene && object.getScene) {
  83170. this._scene = object.getScene();
  83171. }
  83172. if (!this._scene) {
  83173. return;
  83174. }
  83175. this._physicsEngine = this._scene.getPhysicsEngine();
  83176. if (!this._physicsEngine) {
  83177. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83178. }
  83179. else {
  83180. //set the object's quaternion, if not set
  83181. if (!this.object.rotationQuaternion) {
  83182. if (this.object.rotation) {
  83183. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83184. }
  83185. else {
  83186. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83187. }
  83188. }
  83189. //default options params
  83190. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83191. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83192. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83193. this._joints = [];
  83194. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83195. if (!this.object.parent || this._options.ignoreParent) {
  83196. this._init();
  83197. }
  83198. else if (this.object.parent.physicsImpostor) {
  83199. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83200. }
  83201. }
  83202. }
  83203. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83204. get: function () {
  83205. return this._isDisposed;
  83206. },
  83207. enumerable: true,
  83208. configurable: true
  83209. });
  83210. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83211. get: function () {
  83212. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83213. },
  83214. set: function (value) {
  83215. this.setMass(value);
  83216. },
  83217. enumerable: true,
  83218. configurable: true
  83219. });
  83220. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83221. get: function () {
  83222. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83223. },
  83224. set: function (value) {
  83225. if (!this._physicsEngine) {
  83226. return;
  83227. }
  83228. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83229. },
  83230. enumerable: true,
  83231. configurable: true
  83232. });
  83233. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83234. get: function () {
  83235. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83236. },
  83237. set: function (value) {
  83238. if (!this._physicsEngine) {
  83239. return;
  83240. }
  83241. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83242. },
  83243. enumerable: true,
  83244. configurable: true
  83245. });
  83246. /**
  83247. * This function will completly initialize this impostor.
  83248. * It will create a new body - but only if this mesh has no parent.
  83249. * If it has, this impostor will not be used other than to define the impostor
  83250. * of the child mesh.
  83251. */
  83252. PhysicsImpostor.prototype._init = function () {
  83253. if (!this._physicsEngine) {
  83254. return;
  83255. }
  83256. this._physicsEngine.removeImpostor(this);
  83257. this.physicsBody = null;
  83258. this._parent = this._parent || this._getPhysicsParent();
  83259. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83260. this._physicsEngine.addImpostor(this);
  83261. }
  83262. };
  83263. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83264. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83265. var parentMesh = this.object.parent;
  83266. return parentMesh.physicsImpostor;
  83267. }
  83268. return null;
  83269. };
  83270. /**
  83271. * Should a new body be generated.
  83272. */
  83273. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83274. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83275. };
  83276. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83277. this.forceUpdate();
  83278. };
  83279. /**
  83280. * Force a regeneration of this or the parent's impostor's body.
  83281. * Use under cautious - This will remove all joints already implemented.
  83282. */
  83283. PhysicsImpostor.prototype.forceUpdate = function () {
  83284. this._init();
  83285. if (this.parent && !this._options.ignoreParent) {
  83286. this.parent.forceUpdate();
  83287. }
  83288. };
  83289. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83290. /*public get mesh(): AbstractMesh {
  83291. return this._mesh;
  83292. }*/
  83293. /**
  83294. * Gets the body that holds this impostor. Either its own, or its parent.
  83295. */
  83296. get: function () {
  83297. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83298. },
  83299. /**
  83300. * Set the physics body. Used mainly by the physics engine/plugin
  83301. */
  83302. set: function (physicsBody) {
  83303. if (this._physicsBody && this._physicsEngine) {
  83304. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83305. }
  83306. this._physicsBody = physicsBody;
  83307. this.resetUpdateFlags();
  83308. },
  83309. enumerable: true,
  83310. configurable: true
  83311. });
  83312. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83313. get: function () {
  83314. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83315. },
  83316. set: function (value) {
  83317. this._parent = value;
  83318. },
  83319. enumerable: true,
  83320. configurable: true
  83321. });
  83322. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83323. this._bodyUpdateRequired = false;
  83324. };
  83325. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83326. if (this.object.getBoundingInfo) {
  83327. var q = this.object.rotationQuaternion;
  83328. //reset rotation
  83329. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83330. //calculate the world matrix with no rotation
  83331. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83332. var boundingInfo = this.object.getBoundingInfo();
  83333. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83334. //bring back the rotation
  83335. this.object.rotationQuaternion = q;
  83336. //calculate the world matrix with the new rotation
  83337. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83338. return size;
  83339. }
  83340. else {
  83341. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83342. }
  83343. };
  83344. PhysicsImpostor.prototype.getObjectCenter = function () {
  83345. if (this.object.getBoundingInfo) {
  83346. var boundingInfo = this.object.getBoundingInfo();
  83347. return boundingInfo.boundingBox.centerWorld;
  83348. }
  83349. else {
  83350. return this.object.position;
  83351. }
  83352. };
  83353. /**
  83354. * Get a specific parametes from the options parameter.
  83355. */
  83356. PhysicsImpostor.prototype.getParam = function (paramName) {
  83357. return this._options[paramName];
  83358. };
  83359. /**
  83360. * Sets a specific parameter in the options given to the physics plugin
  83361. */
  83362. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83363. this._options[paramName] = value;
  83364. this._bodyUpdateRequired = true;
  83365. };
  83366. /**
  83367. * Specifically change the body's mass option. Won't recreate the physics body object
  83368. */
  83369. PhysicsImpostor.prototype.setMass = function (mass) {
  83370. if (this.getParam("mass") !== mass) {
  83371. this.setParam("mass", mass);
  83372. }
  83373. if (this._physicsEngine) {
  83374. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83375. }
  83376. };
  83377. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83378. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83379. };
  83380. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83381. if (this._physicsEngine) {
  83382. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83383. }
  83384. };
  83385. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83386. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83387. };
  83388. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83389. if (this._physicsEngine) {
  83390. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83391. }
  83392. };
  83393. /**
  83394. * Execute a function with the physics plugin native code.
  83395. * Provide a function the will have two variables - the world object and the physics body object.
  83396. */
  83397. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83398. if (this._physicsEngine) {
  83399. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83400. }
  83401. };
  83402. /**
  83403. * Register a function that will be executed before the physics world is stepping forward.
  83404. */
  83405. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83406. this._onBeforePhysicsStepCallbacks.push(func);
  83407. };
  83408. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83409. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83410. if (index > -1) {
  83411. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83412. }
  83413. else {
  83414. BABYLON.Tools.Warn("Function to remove was not found");
  83415. }
  83416. };
  83417. /**
  83418. * Register a function that will be executed after the physics step
  83419. */
  83420. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83421. this._onAfterPhysicsStepCallbacks.push(func);
  83422. };
  83423. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83424. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83425. if (index > -1) {
  83426. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83427. }
  83428. else {
  83429. BABYLON.Tools.Warn("Function to remove was not found");
  83430. }
  83431. };
  83432. /**
  83433. * register a function that will be executed when this impostor collides against a different body.
  83434. */
  83435. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83436. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83437. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83438. };
  83439. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83440. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83441. var index = -1;
  83442. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83443. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83444. // chcek the arrays match
  83445. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83446. return collidedAgainstList.indexOf(impostor) > -1;
  83447. });
  83448. if (sameList) {
  83449. index = idx;
  83450. }
  83451. return sameList;
  83452. }
  83453. return false;
  83454. });
  83455. if (found) {
  83456. this._onPhysicsCollideCallbacks.splice(index, 1);
  83457. }
  83458. else {
  83459. BABYLON.Tools.Warn("Function to remove was not found");
  83460. }
  83461. };
  83462. PhysicsImpostor.prototype.getParentsRotation = function () {
  83463. var parent = this.object.parent;
  83464. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83465. while (parent) {
  83466. if (parent.rotationQuaternion) {
  83467. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83468. }
  83469. else {
  83470. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83471. }
  83472. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83473. parent = parent.parent;
  83474. }
  83475. return this._tmpQuat;
  83476. };
  83477. /**
  83478. * Apply a force
  83479. */
  83480. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83481. if (this._physicsEngine) {
  83482. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83483. }
  83484. return this;
  83485. };
  83486. /**
  83487. * Apply an impulse
  83488. */
  83489. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83490. if (this._physicsEngine) {
  83491. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83492. }
  83493. return this;
  83494. };
  83495. /**
  83496. * A help function to create a joint.
  83497. */
  83498. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83499. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83500. this.addJoint(otherImpostor, joint);
  83501. return this;
  83502. };
  83503. /**
  83504. * Add a joint to this impostor with a different impostor.
  83505. */
  83506. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83507. this._joints.push({
  83508. otherImpostor: otherImpostor,
  83509. joint: joint
  83510. });
  83511. if (this._physicsEngine) {
  83512. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83513. }
  83514. return this;
  83515. };
  83516. /**
  83517. * Will keep this body still, in a sleep mode.
  83518. */
  83519. PhysicsImpostor.prototype.sleep = function () {
  83520. if (this._physicsEngine) {
  83521. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83522. }
  83523. return this;
  83524. };
  83525. /**
  83526. * Wake the body up.
  83527. */
  83528. PhysicsImpostor.prototype.wakeUp = function () {
  83529. if (this._physicsEngine) {
  83530. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83531. }
  83532. return this;
  83533. };
  83534. PhysicsImpostor.prototype.clone = function (newObject) {
  83535. if (!newObject)
  83536. return null;
  83537. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83538. };
  83539. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83540. var _this = this;
  83541. //no dispose if no physics engine is available.
  83542. if (!this._physicsEngine) {
  83543. return;
  83544. }
  83545. this._joints.forEach(function (j) {
  83546. if (_this._physicsEngine) {
  83547. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83548. }
  83549. });
  83550. //dispose the physics body
  83551. this._physicsEngine.removeImpostor(this);
  83552. if (this.parent) {
  83553. this.parent.forceUpdate();
  83554. }
  83555. else {
  83556. /*this._object.getChildMeshes().forEach(function(mesh) {
  83557. if (mesh.physicsImpostor) {
  83558. if (disposeChildren) {
  83559. mesh.physicsImpostor.dispose();
  83560. mesh.physicsImpostor = null;
  83561. }
  83562. }
  83563. })*/
  83564. }
  83565. this._isDisposed = true;
  83566. };
  83567. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83568. this._deltaPosition.copyFrom(position);
  83569. };
  83570. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83571. if (!this._deltaRotation) {
  83572. this._deltaRotation = new BABYLON.Quaternion();
  83573. }
  83574. this._deltaRotation.copyFrom(rotation);
  83575. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83576. };
  83577. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83578. if (this._physicsEngine) {
  83579. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83580. }
  83581. return this;
  83582. };
  83583. PhysicsImpostor.prototype.getRadius = function () {
  83584. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83585. };
  83586. /**
  83587. * Sync a bone with this impostor
  83588. * @param bone The bone to sync to the impostor.
  83589. * @param boneMesh The mesh that the bone is influencing.
  83590. * @param jointPivot The pivot of the joint / bone in local space.
  83591. * @param distToJoint Optional distance from the impostor to the joint.
  83592. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83593. */
  83594. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83595. var tempVec = PhysicsImpostor._tmpVecs[0];
  83596. var mesh = this.object;
  83597. if (mesh.rotationQuaternion) {
  83598. if (adjustRotation) {
  83599. var tempQuat = PhysicsImpostor._tmpQuat;
  83600. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83601. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83602. }
  83603. else {
  83604. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83605. }
  83606. }
  83607. tempVec.x = 0;
  83608. tempVec.y = 0;
  83609. tempVec.z = 0;
  83610. if (jointPivot) {
  83611. tempVec.x = jointPivot.x;
  83612. tempVec.y = jointPivot.y;
  83613. tempVec.z = jointPivot.z;
  83614. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83615. if (distToJoint === undefined || distToJoint === null) {
  83616. distToJoint = jointPivot.length();
  83617. }
  83618. tempVec.x *= distToJoint;
  83619. tempVec.y *= distToJoint;
  83620. tempVec.z *= distToJoint;
  83621. }
  83622. if (bone.getParent()) {
  83623. tempVec.addInPlace(mesh.getAbsolutePosition());
  83624. bone.setAbsolutePosition(tempVec, boneMesh);
  83625. }
  83626. else {
  83627. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83628. boneMesh.position.x -= tempVec.x;
  83629. boneMesh.position.y -= tempVec.y;
  83630. boneMesh.position.z -= tempVec.z;
  83631. }
  83632. };
  83633. /**
  83634. * Sync impostor to a bone
  83635. * @param bone The bone that the impostor will be synced to.
  83636. * @param boneMesh The mesh that the bone is influencing.
  83637. * @param jointPivot The pivot of the joint / bone in local space.
  83638. * @param distToJoint Optional distance from the impostor to the joint.
  83639. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83640. * @param boneAxis Optional vector3 axis the bone is aligned with
  83641. */
  83642. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83643. var mesh = this.object;
  83644. if (mesh.rotationQuaternion) {
  83645. if (adjustRotation) {
  83646. var tempQuat = PhysicsImpostor._tmpQuat;
  83647. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83648. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83649. }
  83650. else {
  83651. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83652. }
  83653. }
  83654. var pos = PhysicsImpostor._tmpVecs[0];
  83655. var boneDir = PhysicsImpostor._tmpVecs[1];
  83656. if (!boneAxis) {
  83657. boneAxis = PhysicsImpostor._tmpVecs[2];
  83658. boneAxis.x = 0;
  83659. boneAxis.y = 1;
  83660. boneAxis.z = 0;
  83661. }
  83662. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83663. bone.getAbsolutePositionToRef(boneMesh, pos);
  83664. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83665. distToJoint = jointPivot.length();
  83666. }
  83667. if (distToJoint !== undefined && distToJoint !== null) {
  83668. pos.x += boneDir.x * distToJoint;
  83669. pos.y += boneDir.y * distToJoint;
  83670. pos.z += boneDir.z * distToJoint;
  83671. }
  83672. mesh.setAbsolutePosition(pos);
  83673. };
  83674. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83675. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83676. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83677. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83678. //Impostor types
  83679. PhysicsImpostor.NoImpostor = 0;
  83680. PhysicsImpostor.SphereImpostor = 1;
  83681. PhysicsImpostor.BoxImpostor = 2;
  83682. PhysicsImpostor.PlaneImpostor = 3;
  83683. PhysicsImpostor.MeshImpostor = 4;
  83684. PhysicsImpostor.CylinderImpostor = 7;
  83685. PhysicsImpostor.ParticleImpostor = 8;
  83686. PhysicsImpostor.HeightmapImpostor = 9;
  83687. return PhysicsImpostor;
  83688. }());
  83689. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83690. })(BABYLON || (BABYLON = {}));
  83691. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83692. var BABYLON;
  83693. (function (BABYLON) {
  83694. var PhysicsEngine = /** @class */ (function () {
  83695. function PhysicsEngine(gravity, _physicsPlugin) {
  83696. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83697. this._physicsPlugin = _physicsPlugin;
  83698. //new methods and parameters
  83699. this._impostors = [];
  83700. this._joints = [];
  83701. if (!this._physicsPlugin.isSupported()) {
  83702. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83703. + "Please make sure it is included.");
  83704. }
  83705. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83706. this.setGravity(gravity);
  83707. this.setTimeStep();
  83708. }
  83709. PhysicsEngine.prototype.setGravity = function (gravity) {
  83710. this.gravity = gravity;
  83711. this._physicsPlugin.setGravity(this.gravity);
  83712. };
  83713. /**
  83714. * Set the time step of the physics engine.
  83715. * default is 1/60.
  83716. * To slow it down, enter 1/600 for example.
  83717. * To speed it up, 1/30
  83718. * @param {number} newTimeStep the new timestep to apply to this world.
  83719. */
  83720. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83721. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83722. this._physicsPlugin.setTimeStep(newTimeStep);
  83723. };
  83724. /**
  83725. * Get the time step of the physics engine.
  83726. */
  83727. PhysicsEngine.prototype.getTimeStep = function () {
  83728. return this._physicsPlugin.getTimeStep();
  83729. };
  83730. PhysicsEngine.prototype.dispose = function () {
  83731. this._impostors.forEach(function (impostor) {
  83732. impostor.dispose();
  83733. });
  83734. this._physicsPlugin.dispose();
  83735. };
  83736. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83737. return this._physicsPlugin.name;
  83738. };
  83739. /**
  83740. * Adding a new impostor for the impostor tracking.
  83741. * This will be done by the impostor itself.
  83742. * @param {PhysicsImpostor} impostor the impostor to add
  83743. */
  83744. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83745. impostor.uniqueId = this._impostors.push(impostor);
  83746. //if no parent, generate the body
  83747. if (!impostor.parent) {
  83748. this._physicsPlugin.generatePhysicsBody(impostor);
  83749. }
  83750. };
  83751. /**
  83752. * Remove an impostor from the engine.
  83753. * This impostor and its mesh will not longer be updated by the physics engine.
  83754. * @param {PhysicsImpostor} impostor the impostor to remove
  83755. */
  83756. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83757. var index = this._impostors.indexOf(impostor);
  83758. if (index > -1) {
  83759. var removed = this._impostors.splice(index, 1);
  83760. //Is it needed?
  83761. if (removed.length) {
  83762. //this will also remove it from the world.
  83763. removed[0].physicsBody = null;
  83764. }
  83765. }
  83766. };
  83767. /**
  83768. * Add a joint to the physics engine
  83769. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83770. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83771. * @param {PhysicsJoint} the joint that will connect both impostors.
  83772. */
  83773. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83774. var impostorJoint = {
  83775. mainImpostor: mainImpostor,
  83776. connectedImpostor: connectedImpostor,
  83777. joint: joint
  83778. };
  83779. joint.physicsPlugin = this._physicsPlugin;
  83780. this._joints.push(impostorJoint);
  83781. this._physicsPlugin.generateJoint(impostorJoint);
  83782. };
  83783. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83784. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83785. return (impostorJoint.connectedImpostor === connectedImpostor
  83786. && impostorJoint.joint === joint
  83787. && impostorJoint.mainImpostor === mainImpostor);
  83788. });
  83789. if (matchingJoints.length) {
  83790. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83791. //TODO remove it from the list as well
  83792. }
  83793. };
  83794. /**
  83795. * Called by the scene. no need to call it.
  83796. */
  83797. PhysicsEngine.prototype._step = function (delta) {
  83798. var _this = this;
  83799. //check if any mesh has no body / requires an update
  83800. this._impostors.forEach(function (impostor) {
  83801. if (impostor.isBodyInitRequired()) {
  83802. _this._physicsPlugin.generatePhysicsBody(impostor);
  83803. }
  83804. });
  83805. if (delta > 0.1) {
  83806. delta = 0.1;
  83807. }
  83808. else if (delta <= 0) {
  83809. delta = 1.0 / 60.0;
  83810. }
  83811. this._physicsPlugin.executeStep(delta, this._impostors);
  83812. };
  83813. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83814. return this._physicsPlugin;
  83815. };
  83816. PhysicsEngine.prototype.getImpostors = function () {
  83817. return this._impostors;
  83818. };
  83819. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83820. for (var i = 0; i < this._impostors.length; ++i) {
  83821. if (this._impostors[i].object === object) {
  83822. return this._impostors[i];
  83823. }
  83824. }
  83825. return null;
  83826. };
  83827. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83828. for (var i = 0; i < this._impostors.length; ++i) {
  83829. if (this._impostors[i].physicsBody === body) {
  83830. return this._impostors[i];
  83831. }
  83832. }
  83833. return null;
  83834. };
  83835. // Statics
  83836. PhysicsEngine.Epsilon = 0.001;
  83837. return PhysicsEngine;
  83838. }());
  83839. BABYLON.PhysicsEngine = PhysicsEngine;
  83840. })(BABYLON || (BABYLON = {}));
  83841. //# sourceMappingURL=babylon.physicsEngine.js.map
  83842. var BABYLON;
  83843. (function (BABYLON) {
  83844. var PhysicsHelper = /** @class */ (function () {
  83845. function PhysicsHelper(scene) {
  83846. this._scene = scene;
  83847. this._physicsEngine = this._scene.getPhysicsEngine();
  83848. if (!this._physicsEngine) {
  83849. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83850. }
  83851. }
  83852. /**
  83853. * @param {Vector3} origin the origin of the explosion
  83854. * @param {number} radius the explosion radius
  83855. * @param {number} strength the explosion strength
  83856. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83857. */
  83858. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83859. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83860. if (!this._physicsEngine) {
  83861. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83862. return null;
  83863. }
  83864. var impostors = this._physicsEngine.getImpostors();
  83865. if (impostors.length === 0) {
  83866. return null;
  83867. }
  83868. var event = new PhysicsRadialExplosionEvent(this._scene);
  83869. impostors.forEach(function (impostor) {
  83870. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83871. if (!impostorForceAndContactPoint) {
  83872. return;
  83873. }
  83874. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83875. });
  83876. event.dispose(false);
  83877. return event;
  83878. };
  83879. /**
  83880. * @param {Vector3} origin the origin of the explosion
  83881. * @param {number} radius the explosion radius
  83882. * @param {number} strength the explosion strength
  83883. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83884. */
  83885. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83886. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83887. if (!this._physicsEngine) {
  83888. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83889. return null;
  83890. }
  83891. var impostors = this._physicsEngine.getImpostors();
  83892. if (impostors.length === 0) {
  83893. return null;
  83894. }
  83895. var event = new PhysicsRadialExplosionEvent(this._scene);
  83896. impostors.forEach(function (impostor) {
  83897. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83898. if (!impostorForceAndContactPoint) {
  83899. return;
  83900. }
  83901. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83902. });
  83903. event.dispose(false);
  83904. return event;
  83905. };
  83906. /**
  83907. * @param {Vector3} origin the origin of the explosion
  83908. * @param {number} radius the explosion radius
  83909. * @param {number} strength the explosion strength
  83910. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83911. */
  83912. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83913. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83914. if (!this._physicsEngine) {
  83915. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83916. return null;
  83917. }
  83918. var impostors = this._physicsEngine.getImpostors();
  83919. if (impostors.length === 0) {
  83920. return null;
  83921. }
  83922. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83923. event.dispose(false);
  83924. return event;
  83925. };
  83926. /**
  83927. * @param {Vector3} origin the origin of the updraft
  83928. * @param {number} radius the radius of the updraft
  83929. * @param {number} strength the strength of the updraft
  83930. * @param {number} height the height of the updraft
  83931. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83932. */
  83933. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83934. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83935. if (!this._physicsEngine) {
  83936. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83937. return null;
  83938. }
  83939. if (this._physicsEngine.getImpostors().length === 0) {
  83940. return null;
  83941. }
  83942. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83943. event.dispose(false);
  83944. return event;
  83945. };
  83946. /**
  83947. * @param {Vector3} origin the of the vortex
  83948. * @param {number} radius the radius of the vortex
  83949. * @param {number} strength the strength of the vortex
  83950. * @param {number} height the height of the vortex
  83951. */
  83952. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83953. if (!this._physicsEngine) {
  83954. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83955. return null;
  83956. }
  83957. if (this._physicsEngine.getImpostors().length === 0) {
  83958. return null;
  83959. }
  83960. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83961. event.dispose(false);
  83962. return event;
  83963. };
  83964. return PhysicsHelper;
  83965. }());
  83966. BABYLON.PhysicsHelper = PhysicsHelper;
  83967. /***** Radial explosion *****/
  83968. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83969. function PhysicsRadialExplosionEvent(scene) {
  83970. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83971. this._rays = [];
  83972. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83973. this._scene = scene;
  83974. }
  83975. /**
  83976. * Returns the data related to the radial explosion event (sphere & rays).
  83977. * @returns {PhysicsRadialExplosionEventData}
  83978. */
  83979. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83980. this._dataFetched = true;
  83981. return {
  83982. sphere: this._sphere,
  83983. rays: this._rays,
  83984. };
  83985. };
  83986. /**
  83987. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83988. * @param impostor
  83989. * @param {Vector3} origin the origin of the explosion
  83990. * @param {number} radius the explosion radius
  83991. * @param {number} strength the explosion strength
  83992. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83993. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83994. */
  83995. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83996. if (impostor.mass === 0) {
  83997. return null;
  83998. }
  83999. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84000. return null;
  84001. }
  84002. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84003. return null;
  84004. }
  84005. var impostorObjectCenter = impostor.getObjectCenter();
  84006. var direction = impostorObjectCenter.subtract(origin);
  84007. var ray = new BABYLON.Ray(origin, direction, radius);
  84008. this._rays.push(ray);
  84009. var hit = ray.intersectsMesh(impostor.object);
  84010. var contactPoint = hit.pickedPoint;
  84011. if (!contactPoint) {
  84012. return null;
  84013. }
  84014. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84015. if (distanceFromOrigin > radius) {
  84016. return null;
  84017. }
  84018. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84019. ? strength
  84020. : strength * (1 - (distanceFromOrigin / radius));
  84021. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84022. return { force: force, contactPoint: contactPoint };
  84023. };
  84024. /**
  84025. * Disposes the sphere.
  84026. * @param {bolean} force
  84027. */
  84028. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84029. var _this = this;
  84030. if (force === void 0) { force = true; }
  84031. if (force) {
  84032. this._sphere.dispose();
  84033. }
  84034. else {
  84035. setTimeout(function () {
  84036. if (!_this._dataFetched) {
  84037. _this._sphere.dispose();
  84038. }
  84039. }, 0);
  84040. }
  84041. };
  84042. /*** Helpers ***/
  84043. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84044. if (!this._sphere) {
  84045. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84046. this._sphere.isVisible = false;
  84047. }
  84048. };
  84049. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84050. var impostorObject = impostor.object;
  84051. this._prepareSphere();
  84052. this._sphere.position = origin;
  84053. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84054. this._sphere._updateBoundingInfo();
  84055. this._sphere.computeWorldMatrix(true);
  84056. return this._sphere.intersectsMesh(impostorObject, true);
  84057. };
  84058. return PhysicsRadialExplosionEvent;
  84059. }());
  84060. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84061. /***** Gravitational Field *****/
  84062. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84063. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84064. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84065. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84066. this._physicsHelper = physicsHelper;
  84067. this._scene = scene;
  84068. this._origin = origin;
  84069. this._radius = radius;
  84070. this._strength = strength;
  84071. this._falloff = falloff;
  84072. this._tickCallback = this._tick.bind(this);
  84073. }
  84074. /**
  84075. * Returns the data related to the gravitational field event (sphere).
  84076. * @returns {PhysicsGravitationalFieldEventData}
  84077. */
  84078. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84079. this._dataFetched = true;
  84080. return {
  84081. sphere: this._sphere,
  84082. };
  84083. };
  84084. /**
  84085. * Enables the gravitational field.
  84086. */
  84087. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84088. this._tickCallback.call(this);
  84089. this._scene.registerBeforeRender(this._tickCallback);
  84090. };
  84091. /**
  84092. * Disables the gravitational field.
  84093. */
  84094. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84095. this._scene.unregisterBeforeRender(this._tickCallback);
  84096. };
  84097. /**
  84098. * Disposes the sphere.
  84099. * @param {bolean} force
  84100. */
  84101. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84102. var _this = this;
  84103. if (force === void 0) { force = true; }
  84104. if (force) {
  84105. this._sphere.dispose();
  84106. }
  84107. else {
  84108. setTimeout(function () {
  84109. if (!_this._dataFetched) {
  84110. _this._sphere.dispose();
  84111. }
  84112. }, 0);
  84113. }
  84114. };
  84115. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84116. // Since the params won't change, we fetch the event only once
  84117. if (this._sphere) {
  84118. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84119. }
  84120. else {
  84121. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84122. if (radialExplosionEvent) {
  84123. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84124. }
  84125. }
  84126. };
  84127. return PhysicsGravitationalFieldEvent;
  84128. }());
  84129. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84130. /***** Updraft *****/
  84131. var PhysicsUpdraftEvent = /** @class */ (function () {
  84132. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84133. this._scene = _scene;
  84134. this._origin = _origin;
  84135. this._radius = _radius;
  84136. this._strength = _strength;
  84137. this._height = _height;
  84138. this._updraftMode = _updraftMode;
  84139. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84140. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84141. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84142. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84143. this._physicsEngine = this._scene.getPhysicsEngine();
  84144. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84145. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84146. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84147. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84148. }
  84149. this._tickCallback = this._tick.bind(this);
  84150. }
  84151. /**
  84152. * Returns the data related to the updraft event (cylinder).
  84153. * @returns {PhysicsUpdraftEventData}
  84154. */
  84155. PhysicsUpdraftEvent.prototype.getData = function () {
  84156. this._dataFetched = true;
  84157. return {
  84158. cylinder: this._cylinder,
  84159. };
  84160. };
  84161. /**
  84162. * Enables the updraft.
  84163. */
  84164. PhysicsUpdraftEvent.prototype.enable = function () {
  84165. this._tickCallback.call(this);
  84166. this._scene.registerBeforeRender(this._tickCallback);
  84167. };
  84168. /**
  84169. * Disables the cortex.
  84170. */
  84171. PhysicsUpdraftEvent.prototype.disable = function () {
  84172. this._scene.unregisterBeforeRender(this._tickCallback);
  84173. };
  84174. /**
  84175. * Disposes the sphere.
  84176. * @param {bolean} force
  84177. */
  84178. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84179. var _this = this;
  84180. if (force === void 0) { force = true; }
  84181. if (force) {
  84182. this._cylinder.dispose();
  84183. }
  84184. else {
  84185. setTimeout(function () {
  84186. if (!_this._dataFetched) {
  84187. _this._cylinder.dispose();
  84188. }
  84189. }, 0);
  84190. }
  84191. };
  84192. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84193. if (impostor.mass === 0) {
  84194. return null;
  84195. }
  84196. if (!this._intersectsWithCylinder(impostor)) {
  84197. return null;
  84198. }
  84199. var impostorObjectCenter = impostor.getObjectCenter();
  84200. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84201. var direction = this._originDirection;
  84202. }
  84203. else {
  84204. var direction = impostorObjectCenter.subtract(this._originTop);
  84205. }
  84206. var multiplier = this._strength * -1;
  84207. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84208. return { force: force, contactPoint: impostorObjectCenter };
  84209. };
  84210. PhysicsUpdraftEvent.prototype._tick = function () {
  84211. var _this = this;
  84212. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84213. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84214. if (!impostorForceAndContactPoint) {
  84215. return;
  84216. }
  84217. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84218. });
  84219. };
  84220. /*** Helpers ***/
  84221. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84222. if (!this._cylinder) {
  84223. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84224. height: this._height,
  84225. diameter: this._radius * 2,
  84226. }, this._scene);
  84227. this._cylinder.isVisible = false;
  84228. }
  84229. };
  84230. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84231. var impostorObject = impostor.object;
  84232. this._prepareCylinder();
  84233. this._cylinder.position = this._cylinderPosition;
  84234. return this._cylinder.intersectsMesh(impostorObject, true);
  84235. };
  84236. return PhysicsUpdraftEvent;
  84237. }());
  84238. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84239. /***** Vortex *****/
  84240. var PhysicsVortexEvent = /** @class */ (function () {
  84241. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84242. this._scene = _scene;
  84243. this._origin = _origin;
  84244. this._radius = _radius;
  84245. this._strength = _strength;
  84246. this._height = _height;
  84247. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84248. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84249. this._updraftMultiplier = 0.02;
  84250. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84251. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84252. this._physicsEngine = this._scene.getPhysicsEngine();
  84253. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84254. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84255. this._tickCallback = this._tick.bind(this);
  84256. }
  84257. /**
  84258. * Returns the data related to the vortex event (cylinder).
  84259. * @returns {PhysicsVortexEventData}
  84260. */
  84261. PhysicsVortexEvent.prototype.getData = function () {
  84262. this._dataFetched = true;
  84263. return {
  84264. cylinder: this._cylinder,
  84265. };
  84266. };
  84267. /**
  84268. * Enables the vortex.
  84269. */
  84270. PhysicsVortexEvent.prototype.enable = function () {
  84271. this._tickCallback.call(this);
  84272. this._scene.registerBeforeRender(this._tickCallback);
  84273. };
  84274. /**
  84275. * Disables the cortex.
  84276. */
  84277. PhysicsVortexEvent.prototype.disable = function () {
  84278. this._scene.unregisterBeforeRender(this._tickCallback);
  84279. };
  84280. /**
  84281. * Disposes the sphere.
  84282. * @param {bolean} force
  84283. */
  84284. PhysicsVortexEvent.prototype.dispose = function (force) {
  84285. var _this = this;
  84286. if (force === void 0) { force = true; }
  84287. if (force) {
  84288. this._cylinder.dispose();
  84289. }
  84290. else {
  84291. setTimeout(function () {
  84292. if (!_this._dataFetched) {
  84293. _this._cylinder.dispose();
  84294. }
  84295. }, 0);
  84296. }
  84297. };
  84298. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84299. if (impostor.mass === 0) {
  84300. return null;
  84301. }
  84302. if (!this._intersectsWithCylinder(impostor)) {
  84303. return null;
  84304. }
  84305. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84306. return null;
  84307. }
  84308. var impostorObjectCenter = impostor.getObjectCenter();
  84309. 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)
  84310. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84311. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84312. var hit = ray.intersectsMesh(impostor.object);
  84313. var contactPoint = hit.pickedPoint;
  84314. if (!contactPoint) {
  84315. return null;
  84316. }
  84317. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84318. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84319. var directionToOrigin = contactPoint.normalize();
  84320. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84321. directionToOrigin = directionToOrigin.negate();
  84322. }
  84323. // TODO: find a more physically based solution
  84324. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84325. var forceX = directionToOrigin.x * this._strength / 8;
  84326. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84327. var forceZ = directionToOrigin.z * this._strength / 8;
  84328. }
  84329. else {
  84330. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84331. var forceY = this._originTop.y * this._updraftMultiplier;
  84332. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84333. }
  84334. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84335. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84336. return { force: force, contactPoint: impostorObjectCenter };
  84337. };
  84338. PhysicsVortexEvent.prototype._tick = function () {
  84339. var _this = this;
  84340. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84341. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84342. if (!impostorForceAndContactPoint) {
  84343. return;
  84344. }
  84345. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84346. });
  84347. };
  84348. /*** Helpers ***/
  84349. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84350. if (!this._cylinder) {
  84351. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84352. height: this._height,
  84353. diameter: this._radius * 2,
  84354. }, this._scene);
  84355. this._cylinder.isVisible = false;
  84356. }
  84357. };
  84358. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84359. var impostorObject = impostor.object;
  84360. this._prepareCylinder();
  84361. this._cylinder.position = this._cylinderPosition;
  84362. return this._cylinder.intersectsMesh(impostorObject, true);
  84363. };
  84364. return PhysicsVortexEvent;
  84365. }());
  84366. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84367. /***** Enums *****/
  84368. /**
  84369. * The strenght of the force in correspondence to the distance of the affected object
  84370. */
  84371. var PhysicsRadialImpulseFalloff;
  84372. (function (PhysicsRadialImpulseFalloff) {
  84373. /** Defines that impulse is constant in strength across it's whole radius */
  84374. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84375. /** DEfines that impulse gets weaker if it's further from the origin */
  84376. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84377. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84378. /**
  84379. * The strenght of the force in correspondence to the distance of the affected object
  84380. */
  84381. var PhysicsUpdraftMode;
  84382. (function (PhysicsUpdraftMode) {
  84383. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84384. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84385. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84386. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84387. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84388. })(BABYLON || (BABYLON = {}));
  84389. //# sourceMappingURL=babylon.physicsHelper.js.map
  84390. var BABYLON;
  84391. (function (BABYLON) {
  84392. var CannonJSPlugin = /** @class */ (function () {
  84393. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84394. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84395. if (iterations === void 0) { iterations = 10; }
  84396. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84397. this.name = "CannonJSPlugin";
  84398. this._physicsMaterials = new Array();
  84399. this._fixedTimeStep = 1 / 60;
  84400. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84401. this.BJSCANNON = CANNON;
  84402. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84403. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84404. this._tmpPosition = BABYLON.Vector3.Zero();
  84405. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84406. this._tmpUnityRotation = new BABYLON.Quaternion();
  84407. if (!this.isSupported()) {
  84408. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84409. return;
  84410. }
  84411. this._extendNamespace();
  84412. this.world = new this.BJSCANNON.World();
  84413. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84414. this.world.solver.iterations = iterations;
  84415. }
  84416. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84417. this.world.gravity.copy(gravity);
  84418. };
  84419. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84420. this._fixedTimeStep = timeStep;
  84421. };
  84422. CannonJSPlugin.prototype.getTimeStep = function () {
  84423. return this._fixedTimeStep;
  84424. };
  84425. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84426. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84427. };
  84428. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84429. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84430. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84431. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84432. };
  84433. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84434. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84435. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84436. impostor.physicsBody.applyForce(impulse, worldPoint);
  84437. };
  84438. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84439. //parent-child relationship. Does this impostor has a parent impostor?
  84440. if (impostor.parent) {
  84441. if (impostor.physicsBody) {
  84442. this.removePhysicsBody(impostor);
  84443. //TODO is that needed?
  84444. impostor.forceUpdate();
  84445. }
  84446. return;
  84447. }
  84448. //should a new body be created for this impostor?
  84449. if (impostor.isBodyInitRequired()) {
  84450. var shape = this._createShape(impostor);
  84451. //unregister events, if body is being changed
  84452. var oldBody = impostor.physicsBody;
  84453. if (oldBody) {
  84454. this.removePhysicsBody(impostor);
  84455. }
  84456. //create the body and material
  84457. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84458. var bodyCreationObject = {
  84459. mass: impostor.getParam("mass"),
  84460. material: material
  84461. };
  84462. // A simple extend, in case native options were used.
  84463. var nativeOptions = impostor.getParam("nativeOptions");
  84464. for (var key in nativeOptions) {
  84465. if (nativeOptions.hasOwnProperty(key)) {
  84466. bodyCreationObject[key] = nativeOptions[key];
  84467. }
  84468. }
  84469. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84470. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84471. this.world.addEventListener("preStep", impostor.beforeStep);
  84472. this.world.addEventListener("postStep", impostor.afterStep);
  84473. impostor.physicsBody.addShape(shape);
  84474. this.world.add(impostor.physicsBody);
  84475. //try to keep the body moving in the right direction by taking old properties.
  84476. //Should be tested!
  84477. if (oldBody) {
  84478. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84479. impostor.physicsBody[param].copy(oldBody[param]);
  84480. });
  84481. }
  84482. this._processChildMeshes(impostor);
  84483. }
  84484. //now update the body's transformation
  84485. this._updatePhysicsBodyTransformation(impostor);
  84486. };
  84487. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84488. var _this = this;
  84489. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84490. var currentRotation = mainImpostor.object.rotationQuaternion;
  84491. if (meshChildren.length) {
  84492. var processMesh = function (localPosition, mesh) {
  84493. if (!currentRotation || !mesh.rotationQuaternion) {
  84494. return;
  84495. }
  84496. var childImpostor = mesh.getPhysicsImpostor();
  84497. if (childImpostor) {
  84498. var parent = childImpostor.parent;
  84499. if (parent !== mainImpostor) {
  84500. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84501. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84502. if (childImpostor.physicsBody) {
  84503. _this.removePhysicsBody(childImpostor);
  84504. childImpostor.physicsBody = null;
  84505. }
  84506. childImpostor.parent = mainImpostor;
  84507. childImpostor.resetUpdateFlags();
  84508. 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));
  84509. //Add the mass of the children.
  84510. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84511. }
  84512. }
  84513. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84514. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84515. };
  84516. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84517. }
  84518. };
  84519. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84520. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84521. this.world.removeEventListener("preStep", impostor.beforeStep);
  84522. this.world.removeEventListener("postStep", impostor.afterStep);
  84523. this.world.remove(impostor.physicsBody);
  84524. };
  84525. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84526. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84527. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84528. if (!mainBody || !connectedBody) {
  84529. return;
  84530. }
  84531. var constraint;
  84532. var jointData = impostorJoint.joint.jointData;
  84533. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84534. var constraintData = {
  84535. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84536. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84537. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84538. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84539. maxForce: jointData.nativeParams.maxForce,
  84540. collideConnected: !!jointData.collision
  84541. };
  84542. switch (impostorJoint.joint.type) {
  84543. case BABYLON.PhysicsJoint.HingeJoint:
  84544. case BABYLON.PhysicsJoint.Hinge2Joint:
  84545. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84546. break;
  84547. case BABYLON.PhysicsJoint.DistanceJoint:
  84548. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84549. break;
  84550. case BABYLON.PhysicsJoint.SpringJoint:
  84551. var springData = jointData;
  84552. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84553. restLength: springData.length,
  84554. stiffness: springData.stiffness,
  84555. damping: springData.damping,
  84556. localAnchorA: constraintData.pivotA,
  84557. localAnchorB: constraintData.pivotB
  84558. });
  84559. break;
  84560. case BABYLON.PhysicsJoint.LockJoint:
  84561. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84562. break;
  84563. case BABYLON.PhysicsJoint.PointToPointJoint:
  84564. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84565. default:
  84566. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84567. break;
  84568. }
  84569. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84570. constraint.collideConnected = !!jointData.collision;
  84571. impostorJoint.joint.physicsJoint = constraint;
  84572. //don't add spring as constraint, as it is not one.
  84573. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84574. this.world.addConstraint(constraint);
  84575. }
  84576. else {
  84577. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84578. constraint.applyForce();
  84579. });
  84580. }
  84581. };
  84582. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84583. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84584. };
  84585. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84586. var index;
  84587. var mat;
  84588. for (index = 0; index < this._physicsMaterials.length; index++) {
  84589. mat = this._physicsMaterials[index];
  84590. if (mat.friction === friction && mat.restitution === restitution) {
  84591. return mat;
  84592. }
  84593. }
  84594. var currentMat = new this.BJSCANNON.Material(name);
  84595. currentMat.friction = friction;
  84596. currentMat.restitution = restitution;
  84597. this._physicsMaterials.push(currentMat);
  84598. return currentMat;
  84599. };
  84600. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84601. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84602. };
  84603. CannonJSPlugin.prototype._createShape = function (impostor) {
  84604. var object = impostor.object;
  84605. var returnValue;
  84606. var extendSize = impostor.getObjectExtendSize();
  84607. switch (impostor.type) {
  84608. case BABYLON.PhysicsImpostor.SphereImpostor:
  84609. var radiusX = extendSize.x;
  84610. var radiusY = extendSize.y;
  84611. var radiusZ = extendSize.z;
  84612. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84613. break;
  84614. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84615. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84616. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84617. break;
  84618. case BABYLON.PhysicsImpostor.BoxImpostor:
  84619. var box = extendSize.scale(0.5);
  84620. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84621. break;
  84622. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84623. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84624. returnValue = new this.BJSCANNON.Plane();
  84625. break;
  84626. case BABYLON.PhysicsImpostor.MeshImpostor:
  84627. // should transform the vertex data to world coordinates!!
  84628. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84629. var rawFaces = object.getIndices ? object.getIndices() : [];
  84630. if (!rawVerts)
  84631. return;
  84632. // get only scale! so the object could transform correctly.
  84633. var oldPosition = object.position.clone();
  84634. var oldRotation = object.rotation && object.rotation.clone();
  84635. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84636. object.position.copyFromFloats(0, 0, 0);
  84637. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84638. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84639. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84640. var transform = object.computeWorldMatrix(true);
  84641. // convert rawVerts to object space
  84642. var temp = new Array();
  84643. var index;
  84644. for (index = 0; index < rawVerts.length; index += 3) {
  84645. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84646. }
  84647. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84648. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84649. //now set back the transformation!
  84650. object.position.copyFrom(oldPosition);
  84651. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84652. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84653. break;
  84654. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84655. var oldPosition2 = object.position.clone();
  84656. var oldRotation2 = object.rotation && object.rotation.clone();
  84657. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84658. object.position.copyFromFloats(0, 0, 0);
  84659. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84660. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84661. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84662. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84663. returnValue = this._createHeightmap(object);
  84664. object.position.copyFrom(oldPosition2);
  84665. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84666. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84667. object.computeWorldMatrix(true);
  84668. break;
  84669. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84670. returnValue = new this.BJSCANNON.Particle();
  84671. break;
  84672. }
  84673. return returnValue;
  84674. };
  84675. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84676. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84677. var transform = object.computeWorldMatrix(true);
  84678. // convert rawVerts to object space
  84679. var temp = new Array();
  84680. var index;
  84681. for (index = 0; index < pos.length; index += 3) {
  84682. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84683. }
  84684. pos = temp;
  84685. var matrix = new Array();
  84686. //For now pointDepth will not be used and will be automatically calculated.
  84687. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84688. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84689. var boundingInfo = object.getBoundingInfo();
  84690. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84691. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84692. var elementSize = dim * 2 / arraySize;
  84693. for (var i = 0; i < pos.length; i = i + 3) {
  84694. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84695. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84696. var y = -pos[i + 2] + minY;
  84697. if (!matrix[x]) {
  84698. matrix[x] = [];
  84699. }
  84700. if (!matrix[x][z]) {
  84701. matrix[x][z] = y;
  84702. }
  84703. matrix[x][z] = Math.max(y, matrix[x][z]);
  84704. }
  84705. for (var x = 0; x <= arraySize; ++x) {
  84706. if (!matrix[x]) {
  84707. var loc = 1;
  84708. while (!matrix[(x + loc) % arraySize]) {
  84709. loc++;
  84710. }
  84711. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84712. //console.log("missing x", x);
  84713. }
  84714. for (var z = 0; z <= arraySize; ++z) {
  84715. if (!matrix[x][z]) {
  84716. var loc = 1;
  84717. var newValue;
  84718. while (newValue === undefined) {
  84719. newValue = matrix[x][(z + loc++) % arraySize];
  84720. }
  84721. matrix[x][z] = newValue;
  84722. }
  84723. }
  84724. }
  84725. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84726. elementSize: elementSize
  84727. });
  84728. //For future reference, needed for body transformation
  84729. shape.minY = minY;
  84730. return shape;
  84731. };
  84732. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84733. var object = impostor.object;
  84734. //make sure it is updated...
  84735. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84736. // The delta between the mesh position and the mesh bounding box center
  84737. var bInfo = object.getBoundingInfo();
  84738. if (!bInfo)
  84739. return;
  84740. var center = impostor.getObjectCenter();
  84741. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84742. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84743. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84744. this._tmpPosition.copyFrom(center);
  84745. var quaternion = object.rotationQuaternion;
  84746. if (!quaternion) {
  84747. return;
  84748. }
  84749. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84750. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84751. //-90 DEG in X, precalculated
  84752. quaternion = quaternion.multiply(this._minus90X);
  84753. //Invert! (Precalculated, 90 deg in X)
  84754. //No need to clone. this will never change.
  84755. impostor.setDeltaRotation(this._plus90X);
  84756. }
  84757. //If it is a heightfield, if should be centered.
  84758. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84759. var mesh = object;
  84760. var boundingInfo = mesh.getBoundingInfo();
  84761. //calculate the correct body position:
  84762. var rotationQuaternion = mesh.rotationQuaternion;
  84763. mesh.rotationQuaternion = this._tmpUnityRotation;
  84764. mesh.computeWorldMatrix(true);
  84765. //get original center with no rotation
  84766. var c = center.clone();
  84767. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84768. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84769. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84770. mesh.setPreTransformMatrix(p);
  84771. mesh.computeWorldMatrix(true);
  84772. //calculate the translation
  84773. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84774. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84775. //add it inverted to the delta
  84776. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84777. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84778. //rotation is back
  84779. mesh.rotationQuaternion = rotationQuaternion;
  84780. mesh.setPreTransformMatrix(oldPivot);
  84781. mesh.computeWorldMatrix(true);
  84782. }
  84783. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84784. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84785. //this._tmpPosition.copyFrom(object.position);
  84786. }
  84787. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84788. //Now update the impostor object
  84789. impostor.physicsBody.position.copy(this._tmpPosition);
  84790. impostor.physicsBody.quaternion.copy(quaternion);
  84791. };
  84792. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84793. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84794. if (impostor.object.rotationQuaternion) {
  84795. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84796. }
  84797. };
  84798. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84799. impostor.physicsBody.position.copy(newPosition);
  84800. impostor.physicsBody.quaternion.copy(newRotation);
  84801. };
  84802. CannonJSPlugin.prototype.isSupported = function () {
  84803. return this.BJSCANNON !== undefined;
  84804. };
  84805. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84806. impostor.physicsBody.velocity.copy(velocity);
  84807. };
  84808. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84809. impostor.physicsBody.angularVelocity.copy(velocity);
  84810. };
  84811. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84812. var v = impostor.physicsBody.velocity;
  84813. if (!v) {
  84814. return null;
  84815. }
  84816. return new BABYLON.Vector3(v.x, v.y, v.z);
  84817. };
  84818. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84819. var v = impostor.physicsBody.angularVelocity;
  84820. if (!v) {
  84821. return null;
  84822. }
  84823. return new BABYLON.Vector3(v.x, v.y, v.z);
  84824. };
  84825. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84826. impostor.physicsBody.mass = mass;
  84827. impostor.physicsBody.updateMassProperties();
  84828. };
  84829. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84830. return impostor.physicsBody.mass;
  84831. };
  84832. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84833. return impostor.physicsBody.material.friction;
  84834. };
  84835. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84836. impostor.physicsBody.material.friction = friction;
  84837. };
  84838. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84839. return impostor.physicsBody.material.restitution;
  84840. };
  84841. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84842. impostor.physicsBody.material.restitution = restitution;
  84843. };
  84844. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84845. impostor.physicsBody.sleep();
  84846. };
  84847. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84848. impostor.physicsBody.wakeUp();
  84849. };
  84850. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84851. joint.physicsJoint.distance = maxDistance;
  84852. };
  84853. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84854. // if (!motorIndex) {
  84855. // joint.physicsJoint.enableMotor();
  84856. // }
  84857. // }
  84858. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84859. // if (!motorIndex) {
  84860. // joint.physicsJoint.disableMotor();
  84861. // }
  84862. // }
  84863. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84864. if (!motorIndex) {
  84865. joint.physicsJoint.enableMotor();
  84866. joint.physicsJoint.setMotorSpeed(speed);
  84867. if (maxForce) {
  84868. this.setLimit(joint, maxForce);
  84869. }
  84870. }
  84871. };
  84872. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84873. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84874. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84875. };
  84876. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84877. var body = impostor.physicsBody;
  84878. mesh.position.x = body.position.x;
  84879. mesh.position.y = body.position.y;
  84880. mesh.position.z = body.position.z;
  84881. if (mesh.rotationQuaternion) {
  84882. mesh.rotationQuaternion.x = body.quaternion.x;
  84883. mesh.rotationQuaternion.y = body.quaternion.y;
  84884. mesh.rotationQuaternion.z = body.quaternion.z;
  84885. mesh.rotationQuaternion.w = body.quaternion.w;
  84886. }
  84887. };
  84888. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84889. var shape = impostor.physicsBody.shapes[0];
  84890. return shape.boundingSphereRadius;
  84891. };
  84892. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84893. var shape = impostor.physicsBody.shapes[0];
  84894. result.x = shape.halfExtents.x * 2;
  84895. result.y = shape.halfExtents.y * 2;
  84896. result.z = shape.halfExtents.z * 2;
  84897. };
  84898. CannonJSPlugin.prototype.dispose = function () {
  84899. };
  84900. CannonJSPlugin.prototype._extendNamespace = function () {
  84901. //this will force cannon to execute at least one step when using interpolation
  84902. var step_tmp1 = new this.BJSCANNON.Vec3();
  84903. var Engine = this.BJSCANNON;
  84904. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84905. maxSubSteps = maxSubSteps || 10;
  84906. timeSinceLastCalled = timeSinceLastCalled || 0;
  84907. if (timeSinceLastCalled === 0) {
  84908. this.internalStep(dt);
  84909. this.time += dt;
  84910. }
  84911. else {
  84912. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84913. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84914. var t0 = performance.now();
  84915. for (var i = 0; i !== internalSteps; i++) {
  84916. this.internalStep(dt);
  84917. if (performance.now() - t0 > dt * 1000) {
  84918. break;
  84919. }
  84920. }
  84921. this.time += timeSinceLastCalled;
  84922. var h = this.time % dt;
  84923. var h_div_dt = h / dt;
  84924. var interpvelo = step_tmp1;
  84925. var bodies = this.bodies;
  84926. for (var j = 0; j !== bodies.length; j++) {
  84927. var b = bodies[j];
  84928. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84929. b.position.vsub(b.previousPosition, interpvelo);
  84930. interpvelo.scale(h_div_dt, interpvelo);
  84931. b.position.vadd(interpvelo, b.interpolatedPosition);
  84932. }
  84933. else {
  84934. b.interpolatedPosition.copy(b.position);
  84935. b.interpolatedQuaternion.copy(b.quaternion);
  84936. }
  84937. }
  84938. }
  84939. };
  84940. };
  84941. return CannonJSPlugin;
  84942. }());
  84943. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84944. })(BABYLON || (BABYLON = {}));
  84945. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84946. var BABYLON;
  84947. (function (BABYLON) {
  84948. var OimoJSPlugin = /** @class */ (function () {
  84949. function OimoJSPlugin(iterations) {
  84950. this.name = "OimoJSPlugin";
  84951. this._tmpImpostorsArray = [];
  84952. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84953. this.BJSOIMO = OIMO;
  84954. this.world = new this.BJSOIMO.World({
  84955. iterations: iterations
  84956. });
  84957. this.world.clear();
  84958. }
  84959. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84960. this.world.gravity.copy(gravity);
  84961. };
  84962. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84963. this.world.timeStep = timeStep;
  84964. };
  84965. OimoJSPlugin.prototype.getTimeStep = function () {
  84966. return this.world.timeStep;
  84967. };
  84968. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84969. var _this = this;
  84970. impostors.forEach(function (impostor) {
  84971. impostor.beforeStep();
  84972. });
  84973. this.world.step();
  84974. impostors.forEach(function (impostor) {
  84975. impostor.afterStep();
  84976. //update the ordered impostors array
  84977. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84978. });
  84979. //check for collisions
  84980. var contact = this.world.contacts;
  84981. while (contact !== null) {
  84982. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84983. contact = contact.next;
  84984. continue;
  84985. }
  84986. //is this body colliding with any other? get the impostor
  84987. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84988. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84989. if (!mainImpostor || !collidingImpostor) {
  84990. contact = contact.next;
  84991. continue;
  84992. }
  84993. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84994. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84995. contact = contact.next;
  84996. }
  84997. };
  84998. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84999. var mass = impostor.physicsBody.mass;
  85000. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85001. };
  85002. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85003. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85004. this.applyImpulse(impostor, force, contactPoint);
  85005. };
  85006. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85007. var _this = this;
  85008. //parent-child relationship. Does this impostor has a parent impostor?
  85009. if (impostor.parent) {
  85010. if (impostor.physicsBody) {
  85011. this.removePhysicsBody(impostor);
  85012. //TODO is that needed?
  85013. impostor.forceUpdate();
  85014. }
  85015. return;
  85016. }
  85017. if (impostor.isBodyInitRequired()) {
  85018. var bodyConfig = {
  85019. name: impostor.uniqueId,
  85020. //Oimo must have mass, also for static objects.
  85021. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85022. size: [],
  85023. type: [],
  85024. pos: [],
  85025. posShape: [],
  85026. rot: [],
  85027. rotShape: [],
  85028. move: impostor.getParam("mass") !== 0,
  85029. density: impostor.getParam("mass"),
  85030. friction: impostor.getParam("friction"),
  85031. restitution: impostor.getParam("restitution"),
  85032. //Supporting older versions of Oimo
  85033. world: this.world
  85034. };
  85035. var impostors = [impostor];
  85036. var addToArray = function (parent) {
  85037. if (!parent.getChildMeshes)
  85038. return;
  85039. parent.getChildMeshes().forEach(function (m) {
  85040. if (m.physicsImpostor) {
  85041. impostors.push(m.physicsImpostor);
  85042. //m.physicsImpostor._init();
  85043. }
  85044. });
  85045. };
  85046. addToArray(impostor.object);
  85047. var checkWithEpsilon_1 = function (value) {
  85048. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85049. };
  85050. impostors.forEach(function (i) {
  85051. if (!i.object.rotationQuaternion) {
  85052. return;
  85053. }
  85054. //get the correct bounding box
  85055. var oldQuaternion = i.object.rotationQuaternion;
  85056. var rot = oldQuaternion.toEulerAngles();
  85057. var extendSize = i.getObjectExtendSize();
  85058. var radToDeg = 57.295779513082320876;
  85059. if (i === impostor) {
  85060. var center = impostor.getObjectCenter();
  85061. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85062. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85063. //Can also use Array.prototype.push.apply
  85064. bodyConfig.pos.push(center.x);
  85065. bodyConfig.pos.push(center.y);
  85066. bodyConfig.pos.push(center.z);
  85067. bodyConfig.posShape.push(0, 0, 0);
  85068. //tmp solution
  85069. bodyConfig.rot.push(rot.x * radToDeg);
  85070. bodyConfig.rot.push(rot.y * radToDeg);
  85071. bodyConfig.rot.push(rot.z * radToDeg);
  85072. bodyConfig.rotShape.push(0, 0, 0);
  85073. }
  85074. else {
  85075. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85076. bodyConfig.posShape.push(localPosition.x);
  85077. bodyConfig.posShape.push(localPosition.y);
  85078. bodyConfig.posShape.push(localPosition.z);
  85079. bodyConfig.pos.push(0, 0, 0);
  85080. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85081. bodyConfig.rot.push(0);
  85082. bodyConfig.rot.push(0);
  85083. bodyConfig.rot.push(0);
  85084. bodyConfig.rotShape.push(rot.x * radToDeg);
  85085. bodyConfig.rotShape.push(rot.y * radToDeg);
  85086. bodyConfig.rotShape.push(rot.z * radToDeg);
  85087. }
  85088. // register mesh
  85089. switch (i.type) {
  85090. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85091. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85092. case BABYLON.PhysicsImpostor.SphereImpostor:
  85093. var radiusX = extendSize.x;
  85094. var radiusY = extendSize.y;
  85095. var radiusZ = extendSize.z;
  85096. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85097. bodyConfig.type.push('sphere');
  85098. //due to the way oimo works with compounds, add 3 times
  85099. bodyConfig.size.push(size);
  85100. bodyConfig.size.push(size);
  85101. bodyConfig.size.push(size);
  85102. break;
  85103. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85104. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85105. var sizeY = checkWithEpsilon_1(extendSize.y);
  85106. bodyConfig.type.push('cylinder');
  85107. bodyConfig.size.push(sizeX);
  85108. bodyConfig.size.push(sizeY);
  85109. //due to the way oimo works with compounds, add one more value.
  85110. bodyConfig.size.push(sizeY);
  85111. break;
  85112. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85113. case BABYLON.PhysicsImpostor.BoxImpostor:
  85114. default:
  85115. var sizeX = checkWithEpsilon_1(extendSize.x);
  85116. var sizeY = checkWithEpsilon_1(extendSize.y);
  85117. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85118. bodyConfig.type.push('box');
  85119. //if (i === impostor) {
  85120. bodyConfig.size.push(sizeX);
  85121. bodyConfig.size.push(sizeY);
  85122. bodyConfig.size.push(sizeZ);
  85123. //} else {
  85124. // bodyConfig.size.push(0,0,0);
  85125. //}
  85126. break;
  85127. }
  85128. //actually not needed, but hey...
  85129. i.object.rotationQuaternion = oldQuaternion;
  85130. });
  85131. impostor.physicsBody = this.world.add(bodyConfig);
  85132. }
  85133. else {
  85134. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85135. }
  85136. impostor.setDeltaPosition(this._tmpPositionVector);
  85137. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85138. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85139. };
  85140. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85141. //impostor.physicsBody.dispose();
  85142. //Same as : (older oimo versions)
  85143. this.world.removeRigidBody(impostor.physicsBody);
  85144. };
  85145. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85146. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85147. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85148. if (!mainBody || !connectedBody) {
  85149. return;
  85150. }
  85151. var jointData = impostorJoint.joint.jointData;
  85152. var options = jointData.nativeParams || {};
  85153. var type;
  85154. var nativeJointData = {
  85155. body1: mainBody,
  85156. body2: connectedBody,
  85157. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85158. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85159. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85160. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85161. min: options.min,
  85162. max: options.max,
  85163. collision: options.collision || jointData.collision,
  85164. spring: options.spring,
  85165. //supporting older version of Oimo
  85166. world: this.world
  85167. };
  85168. switch (impostorJoint.joint.type) {
  85169. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85170. type = "jointBall";
  85171. break;
  85172. case BABYLON.PhysicsJoint.SpringJoint:
  85173. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85174. var springData = jointData;
  85175. nativeJointData.min = springData.length || nativeJointData.min;
  85176. //Max should also be set, just make sure it is at least min
  85177. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85178. case BABYLON.PhysicsJoint.DistanceJoint:
  85179. type = "jointDistance";
  85180. nativeJointData.max = jointData.maxDistance;
  85181. break;
  85182. case BABYLON.PhysicsJoint.PrismaticJoint:
  85183. type = "jointPrisme";
  85184. break;
  85185. case BABYLON.PhysicsJoint.SliderJoint:
  85186. type = "jointSlide";
  85187. break;
  85188. case BABYLON.PhysicsJoint.WheelJoint:
  85189. type = "jointWheel";
  85190. break;
  85191. case BABYLON.PhysicsJoint.HingeJoint:
  85192. default:
  85193. type = "jointHinge";
  85194. break;
  85195. }
  85196. nativeJointData.type = type;
  85197. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85198. };
  85199. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85200. //Bug in Oimo prevents us from disposing a joint in the playground
  85201. //joint.joint.physicsJoint.dispose();
  85202. //So we will bruteforce it!
  85203. try {
  85204. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85205. }
  85206. catch (e) {
  85207. BABYLON.Tools.Warn(e);
  85208. }
  85209. };
  85210. OimoJSPlugin.prototype.isSupported = function () {
  85211. return this.BJSOIMO !== undefined;
  85212. };
  85213. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85214. if (!impostor.physicsBody.sleeping) {
  85215. //TODO check that
  85216. /*if (impostor.physicsBody.shapes.next) {
  85217. var parentShape = this._getLastShape(impostor.physicsBody);
  85218. impostor.object.position.copyFrom(parentShape.position);
  85219. console.log(parentShape.position);
  85220. } else {*/
  85221. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85222. //}
  85223. if (impostor.object.rotationQuaternion) {
  85224. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85225. }
  85226. }
  85227. };
  85228. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85229. var body = impostor.physicsBody;
  85230. body.position.copy(newPosition);
  85231. body.orientation.copy(newRotation);
  85232. body.syncShapes();
  85233. body.awake();
  85234. };
  85235. /*private _getLastShape(body: any): any {
  85236. var lastShape = body.shapes;
  85237. while (lastShape.next) {
  85238. lastShape = lastShape.next;
  85239. }
  85240. return lastShape;
  85241. }*/
  85242. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85243. impostor.physicsBody.linearVelocity.copy(velocity);
  85244. };
  85245. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85246. impostor.physicsBody.angularVelocity.copy(velocity);
  85247. };
  85248. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85249. var v = impostor.physicsBody.linearVelocity;
  85250. if (!v) {
  85251. return null;
  85252. }
  85253. return new BABYLON.Vector3(v.x, v.y, v.z);
  85254. };
  85255. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85256. var v = impostor.physicsBody.angularVelocity;
  85257. if (!v) {
  85258. return null;
  85259. }
  85260. return new BABYLON.Vector3(v.x, v.y, v.z);
  85261. };
  85262. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85263. var staticBody = mass === 0;
  85264. //this will actually set the body's density and not its mass.
  85265. //But this is how oimo treats the mass variable.
  85266. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85267. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85268. };
  85269. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85270. return impostor.physicsBody.shapes.density;
  85271. };
  85272. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85273. return impostor.physicsBody.shapes.friction;
  85274. };
  85275. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85276. impostor.physicsBody.shapes.friction = friction;
  85277. };
  85278. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85279. return impostor.physicsBody.shapes.restitution;
  85280. };
  85281. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85282. impostor.physicsBody.shapes.restitution = restitution;
  85283. };
  85284. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85285. impostor.physicsBody.sleep();
  85286. };
  85287. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85288. impostor.physicsBody.awake();
  85289. };
  85290. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85291. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85292. if (minDistance !== void 0) {
  85293. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85294. }
  85295. };
  85296. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85297. //TODO separate rotational and transational motors.
  85298. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85299. if (motor) {
  85300. motor.setMotor(speed, maxForce);
  85301. }
  85302. };
  85303. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85304. //TODO separate rotational and transational motors.
  85305. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85306. if (motor) {
  85307. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85308. }
  85309. };
  85310. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85311. var body = impostor.physicsBody;
  85312. mesh.position.x = body.position.x;
  85313. mesh.position.y = body.position.y;
  85314. mesh.position.z = body.position.z;
  85315. if (mesh.rotationQuaternion) {
  85316. mesh.rotationQuaternion.x = body.orientation.x;
  85317. mesh.rotationQuaternion.y = body.orientation.y;
  85318. mesh.rotationQuaternion.z = body.orientation.z;
  85319. mesh.rotationQuaternion.w = body.orientation.s;
  85320. }
  85321. };
  85322. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85323. return impostor.physicsBody.shapes.radius;
  85324. };
  85325. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85326. var shape = impostor.physicsBody.shapes;
  85327. result.x = shape.halfWidth * 2;
  85328. result.y = shape.halfHeight * 2;
  85329. result.z = shape.halfDepth * 2;
  85330. };
  85331. OimoJSPlugin.prototype.dispose = function () {
  85332. this.world.clear();
  85333. };
  85334. return OimoJSPlugin;
  85335. }());
  85336. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85337. })(BABYLON || (BABYLON = {}));
  85338. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85339. var BABYLON;
  85340. (function (BABYLON) {
  85341. /*
  85342. * Based on jsTGALoader - Javascript loader for TGA file
  85343. * By Vincent Thibault
  85344. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85345. */
  85346. var TGATools = /** @class */ (function () {
  85347. function TGATools() {
  85348. }
  85349. TGATools.GetTGAHeader = function (data) {
  85350. var offset = 0;
  85351. var header = {
  85352. id_length: data[offset++],
  85353. colormap_type: data[offset++],
  85354. image_type: data[offset++],
  85355. colormap_index: data[offset++] | data[offset++] << 8,
  85356. colormap_length: data[offset++] | data[offset++] << 8,
  85357. colormap_size: data[offset++],
  85358. origin: [
  85359. data[offset++] | data[offset++] << 8,
  85360. data[offset++] | data[offset++] << 8
  85361. ],
  85362. width: data[offset++] | data[offset++] << 8,
  85363. height: data[offset++] | data[offset++] << 8,
  85364. pixel_size: data[offset++],
  85365. flags: data[offset++]
  85366. };
  85367. return header;
  85368. };
  85369. TGATools.UploadContent = function (gl, data) {
  85370. // Not enough data to contain header ?
  85371. if (data.length < 19) {
  85372. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85373. return;
  85374. }
  85375. // Read Header
  85376. var offset = 18;
  85377. var header = TGATools.GetTGAHeader(data);
  85378. // Assume it's a valid Targa file.
  85379. if (header.id_length + offset > data.length) {
  85380. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85381. return;
  85382. }
  85383. // Skip not needed data
  85384. offset += header.id_length;
  85385. var use_rle = false;
  85386. var use_pal = false;
  85387. var use_grey = false;
  85388. // Get some informations.
  85389. switch (header.image_type) {
  85390. case TGATools._TYPE_RLE_INDEXED:
  85391. use_rle = true;
  85392. case TGATools._TYPE_INDEXED:
  85393. use_pal = true;
  85394. break;
  85395. case TGATools._TYPE_RLE_RGB:
  85396. use_rle = true;
  85397. case TGATools._TYPE_RGB:
  85398. // use_rgb = true;
  85399. break;
  85400. case TGATools._TYPE_RLE_GREY:
  85401. use_rle = true;
  85402. case TGATools._TYPE_GREY:
  85403. use_grey = true;
  85404. break;
  85405. }
  85406. var pixel_data;
  85407. // var numAlphaBits = header.flags & 0xf;
  85408. var pixel_size = header.pixel_size >> 3;
  85409. var pixel_total = header.width * header.height * pixel_size;
  85410. // Read palettes
  85411. var palettes;
  85412. if (use_pal) {
  85413. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85414. }
  85415. // Read LRE
  85416. if (use_rle) {
  85417. pixel_data = new Uint8Array(pixel_total);
  85418. var c, count, i;
  85419. var localOffset = 0;
  85420. var pixels = new Uint8Array(pixel_size);
  85421. while (offset < pixel_total && localOffset < pixel_total) {
  85422. c = data[offset++];
  85423. count = (c & 0x7f) + 1;
  85424. // RLE pixels
  85425. if (c & 0x80) {
  85426. // Bind pixel tmp array
  85427. for (i = 0; i < pixel_size; ++i) {
  85428. pixels[i] = data[offset++];
  85429. }
  85430. // Copy pixel array
  85431. for (i = 0; i < count; ++i) {
  85432. pixel_data.set(pixels, localOffset + i * pixel_size);
  85433. }
  85434. localOffset += pixel_size * count;
  85435. }
  85436. // Raw pixels
  85437. else {
  85438. count *= pixel_size;
  85439. for (i = 0; i < count; ++i) {
  85440. pixel_data[localOffset + i] = data[offset++];
  85441. }
  85442. localOffset += count;
  85443. }
  85444. }
  85445. }
  85446. // RAW Pixels
  85447. else {
  85448. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85449. }
  85450. // Load to texture
  85451. var x_start, y_start, x_step, y_step, y_end, x_end;
  85452. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85453. default:
  85454. case TGATools._ORIGIN_UL:
  85455. x_start = 0;
  85456. x_step = 1;
  85457. x_end = header.width;
  85458. y_start = 0;
  85459. y_step = 1;
  85460. y_end = header.height;
  85461. break;
  85462. case TGATools._ORIGIN_BL:
  85463. x_start = 0;
  85464. x_step = 1;
  85465. x_end = header.width;
  85466. y_start = header.height - 1;
  85467. y_step = -1;
  85468. y_end = -1;
  85469. break;
  85470. case TGATools._ORIGIN_UR:
  85471. x_start = header.width - 1;
  85472. x_step = -1;
  85473. x_end = -1;
  85474. y_start = 0;
  85475. y_step = 1;
  85476. y_end = header.height;
  85477. break;
  85478. case TGATools._ORIGIN_BR:
  85479. x_start = header.width - 1;
  85480. x_step = -1;
  85481. x_end = -1;
  85482. y_start = header.height - 1;
  85483. y_step = -1;
  85484. y_end = -1;
  85485. break;
  85486. }
  85487. // Load the specify method
  85488. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85489. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85490. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85491. };
  85492. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85493. var image = pixel_data, colormap = palettes;
  85494. var width = header.width, height = header.height;
  85495. var color, i = 0, x, y;
  85496. var imageData = new Uint8Array(width * height * 4);
  85497. for (y = y_start; y !== y_end; y += y_step) {
  85498. for (x = x_start; x !== x_end; x += x_step, i++) {
  85499. color = image[i];
  85500. imageData[(x + width * y) * 4 + 3] = 255;
  85501. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85502. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85503. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85504. }
  85505. }
  85506. return imageData;
  85507. };
  85508. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85509. var image = pixel_data;
  85510. var width = header.width, height = header.height;
  85511. var color, i = 0, x, y;
  85512. var imageData = new Uint8Array(width * height * 4);
  85513. for (y = y_start; y !== y_end; y += y_step) {
  85514. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85515. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85516. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85517. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85518. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85519. imageData[(x + width * y) * 4 + 0] = r;
  85520. imageData[(x + width * y) * 4 + 1] = g;
  85521. imageData[(x + width * y) * 4 + 2] = b;
  85522. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85523. }
  85524. }
  85525. return imageData;
  85526. };
  85527. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85528. var image = pixel_data;
  85529. var width = header.width, height = header.height;
  85530. var i = 0, x, y;
  85531. var imageData = new Uint8Array(width * height * 4);
  85532. for (y = y_start; y !== y_end; y += y_step) {
  85533. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85534. imageData[(x + width * y) * 4 + 3] = 255;
  85535. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85536. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85537. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85538. }
  85539. }
  85540. return imageData;
  85541. };
  85542. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85543. var image = pixel_data;
  85544. var width = header.width, height = header.height;
  85545. var i = 0, x, y;
  85546. var imageData = new Uint8Array(width * height * 4);
  85547. for (y = y_start; y !== y_end; y += y_step) {
  85548. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85549. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85550. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85551. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85552. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85553. }
  85554. }
  85555. return imageData;
  85556. };
  85557. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85558. var image = pixel_data;
  85559. var width = header.width, height = header.height;
  85560. var color, i = 0, x, y;
  85561. var imageData = new Uint8Array(width * height * 4);
  85562. for (y = y_start; y !== y_end; y += y_step) {
  85563. for (x = x_start; x !== x_end; x += x_step, i++) {
  85564. color = image[i];
  85565. imageData[(x + width * y) * 4 + 0] = color;
  85566. imageData[(x + width * y) * 4 + 1] = color;
  85567. imageData[(x + width * y) * 4 + 2] = color;
  85568. imageData[(x + width * y) * 4 + 3] = 255;
  85569. }
  85570. }
  85571. return imageData;
  85572. };
  85573. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85574. var image = pixel_data;
  85575. var width = header.width, height = header.height;
  85576. var i = 0, x, y;
  85577. var imageData = new Uint8Array(width * height * 4);
  85578. for (y = y_start; y !== y_end; y += y_step) {
  85579. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85580. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85581. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85582. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85583. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85584. }
  85585. }
  85586. return imageData;
  85587. };
  85588. //private static _TYPE_NO_DATA = 0;
  85589. TGATools._TYPE_INDEXED = 1;
  85590. TGATools._TYPE_RGB = 2;
  85591. TGATools._TYPE_GREY = 3;
  85592. TGATools._TYPE_RLE_INDEXED = 9;
  85593. TGATools._TYPE_RLE_RGB = 10;
  85594. TGATools._TYPE_RLE_GREY = 11;
  85595. TGATools._ORIGIN_MASK = 0x30;
  85596. TGATools._ORIGIN_SHIFT = 0x04;
  85597. TGATools._ORIGIN_BL = 0x00;
  85598. TGATools._ORIGIN_BR = 0x01;
  85599. TGATools._ORIGIN_UL = 0x02;
  85600. TGATools._ORIGIN_UR = 0x03;
  85601. return TGATools;
  85602. }());
  85603. BABYLON.TGATools = TGATools;
  85604. })(BABYLON || (BABYLON = {}));
  85605. //# sourceMappingURL=babylon.tga.js.map
  85606. var BABYLON;
  85607. (function (BABYLON) {
  85608. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85609. // All values and structures referenced from:
  85610. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85611. var DDS_MAGIC = 0x20534444;
  85612. var
  85613. //DDSD_CAPS = 0x1,
  85614. //DDSD_HEIGHT = 0x2,
  85615. //DDSD_WIDTH = 0x4,
  85616. //DDSD_PITCH = 0x8,
  85617. //DDSD_PIXELFORMAT = 0x1000,
  85618. DDSD_MIPMAPCOUNT = 0x20000;
  85619. //DDSD_LINEARSIZE = 0x80000,
  85620. //DDSD_DEPTH = 0x800000;
  85621. // var DDSCAPS_COMPLEX = 0x8,
  85622. // DDSCAPS_MIPMAP = 0x400000,
  85623. // DDSCAPS_TEXTURE = 0x1000;
  85624. var DDSCAPS2_CUBEMAP = 0x200;
  85625. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85626. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85627. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85628. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85629. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85630. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85631. // DDSCAPS2_VOLUME = 0x200000;
  85632. var
  85633. //DDPF_ALPHAPIXELS = 0x1,
  85634. //DDPF_ALPHA = 0x2,
  85635. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85636. //DDPF_YUV = 0x200,
  85637. DDPF_LUMINANCE = 0x20000;
  85638. function FourCCToInt32(value) {
  85639. return value.charCodeAt(0) +
  85640. (value.charCodeAt(1) << 8) +
  85641. (value.charCodeAt(2) << 16) +
  85642. (value.charCodeAt(3) << 24);
  85643. }
  85644. function Int32ToFourCC(value) {
  85645. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85646. }
  85647. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85648. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85649. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85650. var FOURCC_DX10 = FourCCToInt32("DX10");
  85651. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85652. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85653. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85654. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85655. var headerLengthInt = 31; // The header length in 32 bit ints
  85656. // Offsets into the header array
  85657. var off_magic = 0;
  85658. var off_size = 1;
  85659. var off_flags = 2;
  85660. var off_height = 3;
  85661. var off_width = 4;
  85662. var off_mipmapCount = 7;
  85663. var off_pfFlags = 20;
  85664. var off_pfFourCC = 21;
  85665. var off_RGBbpp = 22;
  85666. var off_RMask = 23;
  85667. var off_GMask = 24;
  85668. var off_BMask = 25;
  85669. var off_AMask = 26;
  85670. // var off_caps1 = 27;
  85671. var off_caps2 = 28;
  85672. // var off_caps3 = 29;
  85673. // var off_caps4 = 30;
  85674. var off_dxgiFormat = 32;
  85675. ;
  85676. var DDSTools = /** @class */ (function () {
  85677. function DDSTools() {
  85678. }
  85679. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85680. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85681. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85682. var mipmapCount = 1;
  85683. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85684. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85685. }
  85686. var fourCC = header[off_pfFourCC];
  85687. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85688. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85689. switch (fourCC) {
  85690. case FOURCC_D3DFMT_R16G16B16A16F:
  85691. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85692. break;
  85693. case FOURCC_D3DFMT_R32G32B32A32F:
  85694. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85695. break;
  85696. case FOURCC_DX10:
  85697. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85698. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85699. break;
  85700. }
  85701. }
  85702. return {
  85703. width: header[off_width],
  85704. height: header[off_height],
  85705. mipmapCount: mipmapCount,
  85706. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85707. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85708. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85709. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85710. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85711. dxgiFormat: dxgiFormat,
  85712. textureType: textureType
  85713. };
  85714. };
  85715. DDSTools._ToHalfFloat = function (value) {
  85716. if (!DDSTools._FloatView) {
  85717. DDSTools._FloatView = new Float32Array(1);
  85718. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85719. }
  85720. DDSTools._FloatView[0] = value;
  85721. var x = DDSTools._Int32View[0];
  85722. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85723. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85724. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85725. /* If zero, or denormal, or exponent underflows too much for a denormal
  85726. * half, return signed zero. */
  85727. if (e < 103) {
  85728. return bits;
  85729. }
  85730. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85731. if (e > 142) {
  85732. bits |= 0x7c00;
  85733. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85734. * not Inf, so make sure we set one mantissa bit too. */
  85735. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85736. return bits;
  85737. }
  85738. /* If exponent underflows but not too much, return a denormal */
  85739. if (e < 113) {
  85740. m |= 0x0800;
  85741. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85742. * to 1, which is OK. */
  85743. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85744. return bits;
  85745. }
  85746. bits |= ((e - 112) << 10) | (m >> 1);
  85747. bits += m & 1;
  85748. return bits;
  85749. };
  85750. DDSTools._FromHalfFloat = function (value) {
  85751. var s = (value & 0x8000) >> 15;
  85752. var e = (value & 0x7C00) >> 10;
  85753. var f = value & 0x03FF;
  85754. if (e === 0) {
  85755. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85756. }
  85757. else if (e == 0x1F) {
  85758. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85759. }
  85760. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85761. };
  85762. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85763. var destArray = new Float32Array(dataLength);
  85764. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85765. var index = 0;
  85766. for (var y = 0; y < height; y++) {
  85767. for (var x = 0; x < width; x++) {
  85768. var srcPos = (x + y * width) * 4;
  85769. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85770. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85771. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85772. if (DDSTools.StoreLODInAlphaChannel) {
  85773. destArray[index + 3] = lod;
  85774. }
  85775. else {
  85776. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85777. }
  85778. index += 4;
  85779. }
  85780. }
  85781. return destArray;
  85782. };
  85783. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85784. if (DDSTools.StoreLODInAlphaChannel) {
  85785. var destArray = new Uint16Array(dataLength);
  85786. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85787. var index = 0;
  85788. for (var y = 0; y < height; y++) {
  85789. for (var x = 0; x < width; x++) {
  85790. var srcPos = (x + y * width) * 4;
  85791. destArray[index] = srcData[srcPos];
  85792. destArray[index + 1] = srcData[srcPos + 1];
  85793. destArray[index + 2] = srcData[srcPos + 2];
  85794. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85795. index += 4;
  85796. }
  85797. }
  85798. return destArray;
  85799. }
  85800. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85801. };
  85802. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85803. if (DDSTools.StoreLODInAlphaChannel) {
  85804. var destArray = new Float32Array(dataLength);
  85805. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85806. var index = 0;
  85807. for (var y = 0; y < height; y++) {
  85808. for (var x = 0; x < width; x++) {
  85809. var srcPos = (x + y * width) * 4;
  85810. destArray[index] = srcData[srcPos];
  85811. destArray[index + 1] = srcData[srcPos + 1];
  85812. destArray[index + 2] = srcData[srcPos + 2];
  85813. destArray[index + 3] = lod;
  85814. index += 4;
  85815. }
  85816. }
  85817. return destArray;
  85818. }
  85819. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85820. };
  85821. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85822. var destArray = new Uint8Array(dataLength);
  85823. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85824. var index = 0;
  85825. for (var y = 0; y < height; y++) {
  85826. for (var x = 0; x < width; x++) {
  85827. var srcPos = (x + y * width) * 4;
  85828. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85829. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85830. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85831. if (DDSTools.StoreLODInAlphaChannel) {
  85832. destArray[index + 3] = lod;
  85833. }
  85834. else {
  85835. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85836. }
  85837. index += 4;
  85838. }
  85839. }
  85840. return destArray;
  85841. };
  85842. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85843. var destArray = new Uint8Array(dataLength);
  85844. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85845. var index = 0;
  85846. for (var y = 0; y < height; y++) {
  85847. for (var x = 0; x < width; x++) {
  85848. var srcPos = (x + y * width) * 4;
  85849. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85850. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85851. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85852. if (DDSTools.StoreLODInAlphaChannel) {
  85853. destArray[index + 3] = lod;
  85854. }
  85855. else {
  85856. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85857. }
  85858. index += 4;
  85859. }
  85860. }
  85861. return destArray;
  85862. };
  85863. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85864. var byteArray = new Uint8Array(dataLength);
  85865. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85866. var index = 0;
  85867. for (var y = 0; y < height; y++) {
  85868. for (var x = 0; x < width; x++) {
  85869. var srcPos = (x + y * width) * 4;
  85870. byteArray[index] = srcData[srcPos + rOffset];
  85871. byteArray[index + 1] = srcData[srcPos + gOffset];
  85872. byteArray[index + 2] = srcData[srcPos + bOffset];
  85873. byteArray[index + 3] = srcData[srcPos + aOffset];
  85874. index += 4;
  85875. }
  85876. }
  85877. return byteArray;
  85878. };
  85879. DDSTools._ExtractLongWordOrder = function (value) {
  85880. if (value === 0 || value === 255 || value === -16777216) {
  85881. return 0;
  85882. }
  85883. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85884. };
  85885. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85886. var byteArray = new Uint8Array(dataLength);
  85887. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85888. var index = 0;
  85889. for (var y = 0; y < height; y++) {
  85890. for (var x = 0; x < width; x++) {
  85891. var srcPos = (x + y * width) * 3;
  85892. byteArray[index] = srcData[srcPos + rOffset];
  85893. byteArray[index + 1] = srcData[srcPos + gOffset];
  85894. byteArray[index + 2] = srcData[srcPos + bOffset];
  85895. index += 3;
  85896. }
  85897. }
  85898. return byteArray;
  85899. };
  85900. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85901. var byteArray = new Uint8Array(dataLength);
  85902. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85903. var index = 0;
  85904. for (var y = 0; y < height; y++) {
  85905. for (var x = 0; x < width; x++) {
  85906. var srcPos = (x + y * width);
  85907. byteArray[index] = srcData[srcPos];
  85908. index++;
  85909. }
  85910. }
  85911. return byteArray;
  85912. };
  85913. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85914. if (lodIndex === void 0) { lodIndex = -1; }
  85915. var sphericalPolynomialFaces = null;
  85916. if (info.sphericalPolynomial) {
  85917. sphericalPolynomialFaces = new Array();
  85918. }
  85919. var ext = engine.getCaps().s3tc;
  85920. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85921. var fourCC, width, height, dataLength = 0, dataOffset;
  85922. var byteArray, mipmapCount, mip;
  85923. var internalFormat = 0;
  85924. var format = 0;
  85925. var blockBytes = 1;
  85926. if (header[off_magic] !== DDS_MAGIC) {
  85927. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85928. return;
  85929. }
  85930. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85931. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85932. return;
  85933. }
  85934. if (info.isCompressed && !ext) {
  85935. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85936. return;
  85937. }
  85938. var bpp = header[off_RGBbpp];
  85939. dataOffset = header[off_size] + 4;
  85940. var computeFormats = false;
  85941. if (info.isFourCC) {
  85942. fourCC = header[off_pfFourCC];
  85943. switch (fourCC) {
  85944. case FOURCC_DXT1:
  85945. blockBytes = 8;
  85946. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85947. break;
  85948. case FOURCC_DXT3:
  85949. blockBytes = 16;
  85950. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85951. break;
  85952. case FOURCC_DXT5:
  85953. blockBytes = 16;
  85954. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85955. break;
  85956. case FOURCC_D3DFMT_R16G16B16A16F:
  85957. computeFormats = true;
  85958. break;
  85959. case FOURCC_D3DFMT_R32G32B32A32F:
  85960. computeFormats = true;
  85961. break;
  85962. case FOURCC_DX10:
  85963. // There is an additionnal header so dataOffset need to be changed
  85964. dataOffset += 5 * 4; // 5 uints
  85965. var supported = false;
  85966. switch (info.dxgiFormat) {
  85967. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85968. computeFormats = true;
  85969. supported = true;
  85970. break;
  85971. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85972. info.isRGB = true;
  85973. info.isFourCC = false;
  85974. bpp = 32;
  85975. supported = true;
  85976. break;
  85977. }
  85978. if (supported) {
  85979. break;
  85980. }
  85981. default:
  85982. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85983. return;
  85984. }
  85985. }
  85986. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85987. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85988. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85989. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85990. if (computeFormats) {
  85991. format = engine._getWebGLTextureType(info.textureType);
  85992. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85993. }
  85994. mipmapCount = 1;
  85995. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85996. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85997. }
  85998. for (var face = 0; face < faces; face++) {
  85999. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86000. width = header[off_width];
  86001. height = header[off_height];
  86002. for (mip = 0; mip < mipmapCount; ++mip) {
  86003. if (lodIndex === -1 || lodIndex === mip) {
  86004. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86005. var i = (lodIndex === -1) ? mip : 0;
  86006. if (!info.isCompressed && info.isFourCC) {
  86007. dataLength = width * height * 4;
  86008. var floatArray = null;
  86009. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86010. if (bpp === 128) {
  86011. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86012. if (sphericalPolynomialFaces && i == 0) {
  86013. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86014. }
  86015. }
  86016. else if (bpp === 64) {
  86017. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86018. if (sphericalPolynomialFaces && i == 0) {
  86019. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86020. }
  86021. }
  86022. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86023. format = engine._getWebGLTextureType(info.textureType);
  86024. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86025. }
  86026. else {
  86027. if (bpp === 128) {
  86028. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86029. if (sphericalPolynomialFaces && i == 0) {
  86030. sphericalPolynomialFaces.push(floatArray);
  86031. }
  86032. }
  86033. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86034. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86035. if (sphericalPolynomialFaces && i == 0) {
  86036. sphericalPolynomialFaces.push(floatArray);
  86037. }
  86038. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86039. format = engine._getWebGLTextureType(info.textureType);
  86040. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86041. }
  86042. else { // 64
  86043. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86044. if (sphericalPolynomialFaces && i == 0) {
  86045. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86046. }
  86047. }
  86048. }
  86049. if (floatArray) {
  86050. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86051. }
  86052. }
  86053. else if (info.isRGB) {
  86054. if (bpp === 24) {
  86055. dataLength = width * height * 3;
  86056. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86057. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86058. }
  86059. else { // 32
  86060. dataLength = width * height * 4;
  86061. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86062. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86063. }
  86064. }
  86065. else if (info.isLuminance) {
  86066. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86067. var unpaddedRowSize = width;
  86068. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86069. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86070. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86071. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86072. }
  86073. else {
  86074. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86075. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86076. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86077. }
  86078. }
  86079. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86080. width *= 0.5;
  86081. height *= 0.5;
  86082. width = Math.max(1.0, width);
  86083. height = Math.max(1.0, height);
  86084. }
  86085. if (currentFace !== undefined) {
  86086. // Loading a single face
  86087. break;
  86088. }
  86089. }
  86090. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86091. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86092. size: header[off_width],
  86093. right: sphericalPolynomialFaces[0],
  86094. left: sphericalPolynomialFaces[1],
  86095. up: sphericalPolynomialFaces[2],
  86096. down: sphericalPolynomialFaces[3],
  86097. front: sphericalPolynomialFaces[4],
  86098. back: sphericalPolynomialFaces[5],
  86099. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86100. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86101. gammaSpace: false,
  86102. });
  86103. }
  86104. else {
  86105. info.sphericalPolynomial = undefined;
  86106. }
  86107. };
  86108. DDSTools.StoreLODInAlphaChannel = false;
  86109. return DDSTools;
  86110. }());
  86111. BABYLON.DDSTools = DDSTools;
  86112. })(BABYLON || (BABYLON = {}));
  86113. //# sourceMappingURL=babylon.dds.js.map
  86114. var BABYLON;
  86115. (function (BABYLON) {
  86116. /**
  86117. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86118. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86119. */
  86120. var KhronosTextureContainer = /** @class */ (function () {
  86121. /**
  86122. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86123. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86124. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86125. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86126. */
  86127. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86128. this.arrayBuffer = arrayBuffer;
  86129. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86130. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86131. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86132. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86133. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86134. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86135. BABYLON.Tools.Error("texture missing KTX identifier");
  86136. return;
  86137. }
  86138. // load the reset of the header in native 32 bit int
  86139. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86140. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86141. var oppositeEndianess = header[0] === 0x01020304;
  86142. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86143. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86144. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86145. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86146. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86147. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86148. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86149. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86150. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86151. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86152. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86153. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86154. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86155. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86156. if (this.glType !== 0) {
  86157. BABYLON.Tools.Error("only compressed formats currently supported");
  86158. return;
  86159. }
  86160. else {
  86161. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86162. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86163. }
  86164. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86165. BABYLON.Tools.Error("only 2D textures currently supported");
  86166. return;
  86167. }
  86168. if (this.numberOfArrayElements !== 0) {
  86169. BABYLON.Tools.Error("texture arrays not currently supported");
  86170. return;
  86171. }
  86172. if (this.numberOfFaces !== facesExpected) {
  86173. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86174. return;
  86175. }
  86176. // we now have a completely validated file, so could use existence of loadType as success
  86177. // would need to make this more elaborate & adjust checks above to support more than one load type
  86178. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86179. }
  86180. // not as fast hardware based, but will probably never need to use
  86181. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86182. return ((val & 0xFF) << 24)
  86183. | ((val & 0xFF00) << 8)
  86184. | ((val >> 8) & 0xFF00)
  86185. | ((val >> 24) & 0xFF);
  86186. };
  86187. /**
  86188. * It is assumed that the texture has already been created & is currently bound
  86189. */
  86190. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86191. switch (this.loadType) {
  86192. case KhronosTextureContainer.COMPRESSED_2D:
  86193. this._upload2DCompressedLevels(gl, loadMipmaps);
  86194. break;
  86195. case KhronosTextureContainer.TEX_2D:
  86196. case KhronosTextureContainer.COMPRESSED_3D:
  86197. case KhronosTextureContainer.TEX_3D:
  86198. }
  86199. };
  86200. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86201. // initialize width & height for level 1
  86202. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86203. var width = this.pixelWidth;
  86204. var height = this.pixelHeight;
  86205. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86206. for (var level = 0; level < mipmapCount; level++) {
  86207. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86208. for (var face = 0; face < this.numberOfFaces; face++) {
  86209. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86210. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86211. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86212. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86213. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86214. }
  86215. width = Math.max(1.0, width * 0.5);
  86216. height = Math.max(1.0, height * 0.5);
  86217. }
  86218. };
  86219. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86220. // load types
  86221. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86222. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86223. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86224. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86225. return KhronosTextureContainer;
  86226. }());
  86227. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86228. })(BABYLON || (BABYLON = {}));
  86229. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86230. var BABYLON;
  86231. (function (BABYLON) {
  86232. var Debug;
  86233. (function (Debug) {
  86234. /**
  86235. * Class used to render a debug view of a given skeleton
  86236. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86237. */
  86238. var SkeletonViewer = /** @class */ (function () {
  86239. /**
  86240. * Creates a new SkeletonViewer
  86241. * @param skeleton defines the skeleton to render
  86242. * @param mesh defines the mesh attached to the skeleton
  86243. * @param scene defines the hosting scene
  86244. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86245. * @param renderingGroupId defines the rendering group id to use with the viewer
  86246. */
  86247. function SkeletonViewer(
  86248. /** defines the skeleton to render */
  86249. skeleton,
  86250. /** defines the mesh attached to the skeleton */
  86251. mesh, scene,
  86252. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86253. autoUpdateBonesMatrices,
  86254. /** defines the rendering group id to use with the viewer */
  86255. renderingGroupId) {
  86256. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86257. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86258. this.skeleton = skeleton;
  86259. this.mesh = mesh;
  86260. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86261. this.renderingGroupId = renderingGroupId;
  86262. /** Gets or sets the color used to render the skeleton */
  86263. this.color = BABYLON.Color3.White();
  86264. this._debugLines = new Array();
  86265. this._isEnabled = false;
  86266. this._scene = scene;
  86267. this.update();
  86268. this._renderFunction = this.update.bind(this);
  86269. }
  86270. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86271. get: function () {
  86272. return this._isEnabled;
  86273. },
  86274. /** Gets or sets a boolean indicating if the viewer is enabled */
  86275. set: function (value) {
  86276. if (this._isEnabled === value) {
  86277. return;
  86278. }
  86279. this._isEnabled = value;
  86280. if (value) {
  86281. this._scene.registerBeforeRender(this._renderFunction);
  86282. }
  86283. else {
  86284. this._scene.unregisterBeforeRender(this._renderFunction);
  86285. }
  86286. },
  86287. enumerable: true,
  86288. configurable: true
  86289. });
  86290. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86291. if (x === void 0) { x = 0; }
  86292. if (y === void 0) { y = 0; }
  86293. if (z === void 0) { z = 0; }
  86294. var tmat = BABYLON.Tmp.Matrix[0];
  86295. var parentBone = bone.getParent();
  86296. tmat.copyFrom(bone.getLocalMatrix());
  86297. if (x !== 0 || y !== 0 || z !== 0) {
  86298. var tmat2 = BABYLON.Tmp.Matrix[1];
  86299. BABYLON.Matrix.IdentityToRef(tmat2);
  86300. tmat2.m[12] = x;
  86301. tmat2.m[13] = y;
  86302. tmat2.m[14] = z;
  86303. tmat2.multiplyToRef(tmat, tmat);
  86304. }
  86305. if (parentBone) {
  86306. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86307. }
  86308. tmat.multiplyToRef(meshMat, tmat);
  86309. position.x = tmat.m[12];
  86310. position.y = tmat.m[13];
  86311. position.z = tmat.m[14];
  86312. };
  86313. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86314. var len = bones.length;
  86315. var meshPos = this.mesh.position;
  86316. for (var i = 0; i < len; i++) {
  86317. var bone = bones[i];
  86318. var points = this._debugLines[i];
  86319. if (!points) {
  86320. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86321. this._debugLines[i] = points;
  86322. }
  86323. this._getBonePosition(points[0], bone, meshMat);
  86324. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86325. points[0].subtractInPlace(meshPos);
  86326. points[1].subtractInPlace(meshPos);
  86327. }
  86328. };
  86329. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86330. var len = bones.length;
  86331. var boneNum = 0;
  86332. var meshPos = this.mesh.position;
  86333. for (var i = len - 1; i >= 0; i--) {
  86334. var childBone = bones[i];
  86335. var parentBone = childBone.getParent();
  86336. if (!parentBone) {
  86337. continue;
  86338. }
  86339. var points = this._debugLines[boneNum];
  86340. if (!points) {
  86341. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86342. this._debugLines[boneNum] = points;
  86343. }
  86344. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86345. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86346. points[0].subtractInPlace(meshPos);
  86347. points[1].subtractInPlace(meshPos);
  86348. boneNum++;
  86349. }
  86350. };
  86351. /** Update the viewer to sync with current skeleton state */
  86352. SkeletonViewer.prototype.update = function () {
  86353. if (this.autoUpdateBonesMatrices) {
  86354. this.skeleton.computeAbsoluteTransforms();
  86355. }
  86356. if (this.skeleton.bones[0].length === undefined) {
  86357. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86358. }
  86359. else {
  86360. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86361. }
  86362. if (!this._debugMesh) {
  86363. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86364. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86365. }
  86366. else {
  86367. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86368. }
  86369. this._debugMesh.position.copyFrom(this.mesh.position);
  86370. this._debugMesh.color = this.color;
  86371. };
  86372. /** Release associated resources */
  86373. SkeletonViewer.prototype.dispose = function () {
  86374. if (this._debugMesh) {
  86375. this.isEnabled = false;
  86376. this._debugMesh.dispose();
  86377. this._debugMesh = null;
  86378. }
  86379. };
  86380. return SkeletonViewer;
  86381. }());
  86382. Debug.SkeletonViewer = SkeletonViewer;
  86383. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86384. })(BABYLON || (BABYLON = {}));
  86385. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86386. /**
  86387. * Module Debug contains the (visual) components to debug a scene correctly
  86388. */
  86389. var BABYLON;
  86390. (function (BABYLON) {
  86391. var Debug;
  86392. (function (Debug) {
  86393. /**
  86394. * The Axes viewer will show 3 axes in a specific point in space
  86395. */
  86396. var AxesViewer = /** @class */ (function () {
  86397. /**
  86398. * Creates a new AxesViewer
  86399. * @param scene defines the hosting scene
  86400. * @param scaleLines defines a number used to scale line length (1 by default)
  86401. */
  86402. function AxesViewer(scene, scaleLines) {
  86403. if (scaleLines === void 0) { scaleLines = 1; }
  86404. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86405. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86406. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86407. /**
  86408. * Gets or sets a number used to scale line length
  86409. */
  86410. this.scaleLines = 1;
  86411. this.scaleLines = scaleLines;
  86412. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86413. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86414. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86415. this._xmesh.renderingGroupId = 2;
  86416. this._ymesh.renderingGroupId = 2;
  86417. this._zmesh.renderingGroupId = 2;
  86418. this._xmesh.material.checkReadyOnlyOnce = true;
  86419. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86420. this._ymesh.material.checkReadyOnlyOnce = true;
  86421. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86422. this._zmesh.material.checkReadyOnlyOnce = true;
  86423. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86424. this.scene = scene;
  86425. }
  86426. /**
  86427. * Force the viewer to update
  86428. * @param position defines the position of the viewer
  86429. * @param xaxis defines the x axis of the viewer
  86430. * @param yaxis defines the y axis of the viewer
  86431. * @param zaxis defines the z axis of the viewer
  86432. */
  86433. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86434. var scaleLines = this.scaleLines;
  86435. if (this._xmesh) {
  86436. this._xmesh.position.copyFrom(position);
  86437. }
  86438. if (this._ymesh) {
  86439. this._ymesh.position.copyFrom(position);
  86440. }
  86441. if (this._zmesh) {
  86442. this._zmesh.position.copyFrom(position);
  86443. }
  86444. var point2 = this._xline[1];
  86445. point2.x = xaxis.x * scaleLines;
  86446. point2.y = xaxis.y * scaleLines;
  86447. point2.z = xaxis.z * scaleLines;
  86448. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86449. point2 = this._yline[1];
  86450. point2.x = yaxis.x * scaleLines;
  86451. point2.y = yaxis.y * scaleLines;
  86452. point2.z = yaxis.z * scaleLines;
  86453. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86454. point2 = this._zline[1];
  86455. point2.x = zaxis.x * scaleLines;
  86456. point2.y = zaxis.y * scaleLines;
  86457. point2.z = zaxis.z * scaleLines;
  86458. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86459. };
  86460. /** Releases resources */
  86461. AxesViewer.prototype.dispose = function () {
  86462. if (this._xmesh) {
  86463. this._xmesh.dispose();
  86464. }
  86465. if (this._ymesh) {
  86466. this._ymesh.dispose();
  86467. }
  86468. if (this._zmesh) {
  86469. this._zmesh.dispose();
  86470. }
  86471. this._xmesh = null;
  86472. this._ymesh = null;
  86473. this._zmesh = null;
  86474. this.scene = null;
  86475. };
  86476. return AxesViewer;
  86477. }());
  86478. Debug.AxesViewer = AxesViewer;
  86479. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86480. })(BABYLON || (BABYLON = {}));
  86481. //# sourceMappingURL=babylon.axesViewer.js.map
  86482. var BABYLON;
  86483. (function (BABYLON) {
  86484. var Debug;
  86485. (function (Debug) {
  86486. /**
  86487. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86488. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86489. */
  86490. var BoneAxesViewer = /** @class */ (function (_super) {
  86491. __extends(BoneAxesViewer, _super);
  86492. /**
  86493. * Creates a new BoneAxesViewer
  86494. * @param scene defines the hosting scene
  86495. * @param bone defines the target bone
  86496. * @param mesh defines the target mesh
  86497. * @param scaleLines defines a scaling factor for line length (1 by default)
  86498. */
  86499. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86500. if (scaleLines === void 0) { scaleLines = 1; }
  86501. var _this = _super.call(this, scene, scaleLines) || this;
  86502. /** Gets current position */
  86503. _this.pos = BABYLON.Vector3.Zero();
  86504. /** Gets direction of X axis */
  86505. _this.xaxis = BABYLON.Vector3.Zero();
  86506. /** Gets direction of Y axis */
  86507. _this.yaxis = BABYLON.Vector3.Zero();
  86508. /** Gets direction of Z axis */
  86509. _this.zaxis = BABYLON.Vector3.Zero();
  86510. _this.mesh = mesh;
  86511. _this.bone = bone;
  86512. return _this;
  86513. }
  86514. /**
  86515. * Force the viewer to update
  86516. */
  86517. BoneAxesViewer.prototype.update = function () {
  86518. if (!this.mesh || !this.bone) {
  86519. return;
  86520. }
  86521. var bone = this.bone;
  86522. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86523. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86524. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86525. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86526. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86527. };
  86528. /** Releases resources */
  86529. BoneAxesViewer.prototype.dispose = function () {
  86530. if (this.mesh) {
  86531. this.mesh = null;
  86532. this.bone = null;
  86533. _super.prototype.dispose.call(this);
  86534. }
  86535. };
  86536. return BoneAxesViewer;
  86537. }(Debug.AxesViewer));
  86538. Debug.BoneAxesViewer = BoneAxesViewer;
  86539. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86540. })(BABYLON || (BABYLON = {}));
  86541. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86542. var BABYLON;
  86543. (function (BABYLON) {
  86544. var RayHelper = /** @class */ (function () {
  86545. function RayHelper(ray) {
  86546. this.ray = ray;
  86547. }
  86548. RayHelper.CreateAndShow = function (ray, scene, color) {
  86549. var helper = new RayHelper(ray);
  86550. helper.show(scene, color);
  86551. return helper;
  86552. };
  86553. RayHelper.prototype.show = function (scene, color) {
  86554. if (!this._renderFunction && this.ray) {
  86555. var ray = this.ray;
  86556. this._renderFunction = this._render.bind(this);
  86557. this._scene = scene;
  86558. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86559. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86560. if (this._renderFunction) {
  86561. this._scene.registerBeforeRender(this._renderFunction);
  86562. }
  86563. }
  86564. if (color && this._renderLine) {
  86565. this._renderLine.color.copyFrom(color);
  86566. }
  86567. };
  86568. RayHelper.prototype.hide = function () {
  86569. if (this._renderFunction && this._scene) {
  86570. this._scene.unregisterBeforeRender(this._renderFunction);
  86571. this._scene = null;
  86572. this._renderFunction = null;
  86573. if (this._renderLine) {
  86574. this._renderLine.dispose();
  86575. this._renderLine = null;
  86576. }
  86577. this._renderPoints = [];
  86578. }
  86579. };
  86580. RayHelper.prototype._render = function () {
  86581. var ray = this.ray;
  86582. if (!ray) {
  86583. return;
  86584. }
  86585. var point = this._renderPoints[1];
  86586. var len = Math.min(ray.length, 1000000);
  86587. point.copyFrom(ray.direction);
  86588. point.scaleInPlace(len);
  86589. point.addInPlace(ray.origin);
  86590. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86591. };
  86592. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86593. this._attachedToMesh = mesh;
  86594. var ray = this.ray;
  86595. if (!ray) {
  86596. return;
  86597. }
  86598. if (!ray.direction) {
  86599. ray.direction = BABYLON.Vector3.Zero();
  86600. }
  86601. if (!ray.origin) {
  86602. ray.origin = BABYLON.Vector3.Zero();
  86603. }
  86604. if (length) {
  86605. ray.length = length;
  86606. }
  86607. if (!meshSpaceOrigin) {
  86608. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86609. }
  86610. if (!meshSpaceDirection) {
  86611. // -1 so that this will work with Mesh.lookAt
  86612. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86613. }
  86614. if (!this._meshSpaceDirection) {
  86615. this._meshSpaceDirection = meshSpaceDirection.clone();
  86616. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86617. }
  86618. else {
  86619. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86620. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86621. }
  86622. if (!this._updateToMeshFunction) {
  86623. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86624. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86625. }
  86626. this._updateToMesh();
  86627. };
  86628. RayHelper.prototype.detachFromMesh = function () {
  86629. if (this._attachedToMesh) {
  86630. if (this._updateToMeshFunction) {
  86631. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86632. }
  86633. this._attachedToMesh = null;
  86634. this._updateToMeshFunction = null;
  86635. }
  86636. };
  86637. RayHelper.prototype._updateToMesh = function () {
  86638. var ray = this.ray;
  86639. if (!this._attachedToMesh || !ray) {
  86640. return;
  86641. }
  86642. if (this._attachedToMesh._isDisposed) {
  86643. this.detachFromMesh();
  86644. return;
  86645. }
  86646. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86647. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86648. };
  86649. RayHelper.prototype.dispose = function () {
  86650. this.hide();
  86651. this.detachFromMesh();
  86652. this.ray = null;
  86653. };
  86654. return RayHelper;
  86655. }());
  86656. BABYLON.RayHelper = RayHelper;
  86657. })(BABYLON || (BABYLON = {}));
  86658. //# sourceMappingURL=babylon.rayHelper.js.map
  86659. var BABYLON;
  86660. (function (BABYLON) {
  86661. // load the inspector using require, if not present in the global namespace.
  86662. var DebugLayer = /** @class */ (function () {
  86663. function DebugLayer(scene) {
  86664. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86665. this._scene = scene;
  86666. // load inspector using require, if it doesn't exist on the global namespace.
  86667. }
  86668. /** Creates the inspector window. */
  86669. DebugLayer.prototype._createInspector = function (config) {
  86670. if (config === void 0) { config = {}; }
  86671. var popup = config.popup || false;
  86672. var initialTab = config.initialTab || 0;
  86673. var parentElement = config.parentElement || null;
  86674. if (!this._inspector) {
  86675. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86676. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86677. } // else nothing to do,; instance is already existing
  86678. };
  86679. DebugLayer.prototype.isVisible = function () {
  86680. if (!this._inspector) {
  86681. return false;
  86682. }
  86683. return true;
  86684. };
  86685. DebugLayer.prototype.hide = function () {
  86686. if (this._inspector) {
  86687. try {
  86688. this._inspector.dispose();
  86689. }
  86690. catch (e) {
  86691. // If the inspector has been removed directly from the inspector tool
  86692. }
  86693. this._inspector = null;
  86694. }
  86695. };
  86696. /**
  86697. *
  86698. * Launch the debugLayer.
  86699. *
  86700. * initialTab:
  86701. * | Value | Tab Name |
  86702. * | --- | --- |
  86703. * | 0 | Scene |
  86704. * | 1 | Console |
  86705. * | 2 | Stats |
  86706. * | 3 | Textures |
  86707. * | 4 | Mesh |
  86708. * | 5 | Light |
  86709. * | 6 | Material |
  86710. * | 7 | GLTF |
  86711. * | 8 | GUI |
  86712. * | 9 | Physics |
  86713. * | 10 | Camera |
  86714. * | 11 | Audio |
  86715. *
  86716. */
  86717. DebugLayer.prototype.show = function (config) {
  86718. if (config === void 0) { config = {}; }
  86719. if (typeof this.BJSINSPECTOR == 'undefined') {
  86720. // Load inspector and add it to the DOM
  86721. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86722. }
  86723. else {
  86724. // Otherwise creates the inspector
  86725. this._createInspector(config);
  86726. }
  86727. };
  86728. /**
  86729. * Gets the active tab
  86730. * @return the index of the active tab or -1 if the inspector is hidden
  86731. */
  86732. DebugLayer.prototype.getActiveTab = function () {
  86733. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86734. };
  86735. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86736. return DebugLayer;
  86737. }());
  86738. BABYLON.DebugLayer = DebugLayer;
  86739. })(BABYLON || (BABYLON = {}));
  86740. //# sourceMappingURL=babylon.debugLayer.js.map
  86741. var BABYLON;
  86742. (function (BABYLON) {
  86743. var Debug;
  86744. (function (Debug) {
  86745. /**
  86746. * Used to show the physics impostor around the specific mesh
  86747. */
  86748. var PhysicsViewer = /** @class */ (function () {
  86749. /**
  86750. * Creates a new PhysicsViewer
  86751. * @param scene defines the hosting scene
  86752. */
  86753. function PhysicsViewer(scene) {
  86754. /** @hidden */
  86755. this._impostors = [];
  86756. /** @hidden */
  86757. this._meshes = [];
  86758. /** @hidden */
  86759. this._numMeshes = 0;
  86760. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86761. var physicEngine = this._scene.getPhysicsEngine();
  86762. if (physicEngine) {
  86763. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86764. }
  86765. }
  86766. /** @hidden */
  86767. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86768. var plugin = this._physicsEnginePlugin;
  86769. for (var i = 0; i < this._numMeshes; i++) {
  86770. var impostor = this._impostors[i];
  86771. if (!impostor) {
  86772. continue;
  86773. }
  86774. if (impostor.isDisposed) {
  86775. this.hideImpostor(this._impostors[i--]);
  86776. }
  86777. else {
  86778. var mesh = this._meshes[i];
  86779. if (mesh && plugin) {
  86780. plugin.syncMeshWithImpostor(mesh, impostor);
  86781. }
  86782. }
  86783. }
  86784. };
  86785. /**
  86786. * Renders a specified physic impostor
  86787. * @param impostor defines the impostor to render
  86788. */
  86789. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86790. if (!this._scene) {
  86791. return;
  86792. }
  86793. for (var i = 0; i < this._numMeshes; i++) {
  86794. if (this._impostors[i] == impostor) {
  86795. return;
  86796. }
  86797. }
  86798. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86799. if (debugMesh) {
  86800. this._impostors[this._numMeshes] = impostor;
  86801. this._meshes[this._numMeshes] = debugMesh;
  86802. if (this._numMeshes === 0) {
  86803. this._renderFunction = this._updateDebugMeshes.bind(this);
  86804. this._scene.registerBeforeRender(this._renderFunction);
  86805. }
  86806. this._numMeshes++;
  86807. }
  86808. };
  86809. /**
  86810. * Hides a specified physic impostor
  86811. * @param impostor defines the impostor to hide
  86812. */
  86813. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86814. if (!impostor || !this._scene) {
  86815. return;
  86816. }
  86817. var removed = false;
  86818. for (var i = 0; i < this._numMeshes; i++) {
  86819. if (this._impostors[i] == impostor) {
  86820. var mesh = this._meshes[i];
  86821. if (!mesh) {
  86822. continue;
  86823. }
  86824. this._scene.removeMesh(mesh);
  86825. mesh.dispose();
  86826. this._numMeshes--;
  86827. if (this._numMeshes > 0) {
  86828. this._meshes[i] = this._meshes[this._numMeshes];
  86829. this._impostors[i] = this._impostors[this._numMeshes];
  86830. this._meshes[this._numMeshes] = null;
  86831. this._impostors[this._numMeshes] = null;
  86832. }
  86833. else {
  86834. this._meshes[0] = null;
  86835. this._impostors[0] = null;
  86836. }
  86837. removed = true;
  86838. break;
  86839. }
  86840. }
  86841. if (removed && this._numMeshes === 0) {
  86842. this._scene.unregisterBeforeRender(this._renderFunction);
  86843. }
  86844. };
  86845. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86846. if (!this._debugMaterial) {
  86847. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86848. this._debugMaterial.wireframe = true;
  86849. }
  86850. return this._debugMaterial;
  86851. };
  86852. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86853. if (!this._debugBoxMesh) {
  86854. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86855. this._debugBoxMesh.renderingGroupId = 1;
  86856. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86857. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86858. scene.removeMesh(this._debugBoxMesh);
  86859. }
  86860. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86861. };
  86862. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86863. if (!this._debugSphereMesh) {
  86864. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86865. this._debugSphereMesh.renderingGroupId = 1;
  86866. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86867. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86868. scene.removeMesh(this._debugSphereMesh);
  86869. }
  86870. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86871. };
  86872. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86873. var mesh = null;
  86874. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86875. mesh = this._getDebugBoxMesh(scene);
  86876. impostor.getBoxSizeToRef(mesh.scaling);
  86877. }
  86878. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86879. mesh = this._getDebugSphereMesh(scene);
  86880. var radius = impostor.getRadius();
  86881. mesh.scaling.x = radius * 2;
  86882. mesh.scaling.y = radius * 2;
  86883. mesh.scaling.z = radius * 2;
  86884. }
  86885. return mesh;
  86886. };
  86887. /** Releases all resources */
  86888. PhysicsViewer.prototype.dispose = function () {
  86889. for (var i = 0; i < this._numMeshes; i++) {
  86890. this.hideImpostor(this._impostors[i]);
  86891. }
  86892. if (this._debugBoxMesh) {
  86893. this._debugBoxMesh.dispose();
  86894. }
  86895. if (this._debugSphereMesh) {
  86896. this._debugSphereMesh.dispose();
  86897. }
  86898. if (this._debugMaterial) {
  86899. this._debugMaterial.dispose();
  86900. }
  86901. this._impostors.length = 0;
  86902. this._scene = null;
  86903. this._physicsEnginePlugin = null;
  86904. };
  86905. return PhysicsViewer;
  86906. }());
  86907. Debug.PhysicsViewer = PhysicsViewer;
  86908. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86909. })(BABYLON || (BABYLON = {}));
  86910. //# sourceMappingURL=babylon.physicsViewer.js.map
  86911. var BABYLON;
  86912. (function (BABYLON) {
  86913. var BoundingBoxRenderer = /** @class */ (function () {
  86914. function BoundingBoxRenderer(scene) {
  86915. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86916. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86917. this.showBackLines = true;
  86918. this.renderList = new BABYLON.SmartArray(32);
  86919. this._vertexBuffers = {};
  86920. this._scene = scene;
  86921. }
  86922. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86923. if (this._colorShader) {
  86924. return;
  86925. }
  86926. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86927. attributes: [BABYLON.VertexBuffer.PositionKind],
  86928. uniforms: ["world", "viewProjection", "color"]
  86929. });
  86930. var engine = this._scene.getEngine();
  86931. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86932. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86933. this._createIndexBuffer();
  86934. };
  86935. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86936. var engine = this._scene.getEngine();
  86937. 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]);
  86938. };
  86939. BoundingBoxRenderer.prototype._rebuild = function () {
  86940. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86941. if (vb) {
  86942. vb._rebuild();
  86943. }
  86944. this._createIndexBuffer();
  86945. };
  86946. BoundingBoxRenderer.prototype.reset = function () {
  86947. this.renderList.reset();
  86948. };
  86949. BoundingBoxRenderer.prototype.render = function () {
  86950. if (this.renderList.length === 0) {
  86951. return;
  86952. }
  86953. this._prepareRessources();
  86954. if (!this._colorShader.isReady()) {
  86955. return;
  86956. }
  86957. var engine = this._scene.getEngine();
  86958. engine.setDepthWrite(false);
  86959. this._colorShader._preBind();
  86960. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86961. var boundingBox = this.renderList.data[boundingBoxIndex];
  86962. var min = boundingBox.minimum;
  86963. var max = boundingBox.maximum;
  86964. var diff = max.subtract(min);
  86965. var median = min.add(diff.scale(0.5));
  86966. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86967. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86968. .multiply(boundingBox.getWorldMatrix());
  86969. // VBOs
  86970. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86971. if (this.showBackLines) {
  86972. // Back
  86973. engine.setDepthFunctionToGreaterOrEqual();
  86974. this._scene.resetCachedMaterial();
  86975. this._colorShader.setColor4("color", this.backColor.toColor4());
  86976. this._colorShader.bind(worldMatrix);
  86977. // Draw order
  86978. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86979. }
  86980. // Front
  86981. engine.setDepthFunctionToLess();
  86982. this._scene.resetCachedMaterial();
  86983. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86984. this._colorShader.bind(worldMatrix);
  86985. // Draw order
  86986. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86987. }
  86988. this._colorShader.unbind();
  86989. engine.setDepthFunctionToLessOrEqual();
  86990. engine.setDepthWrite(true);
  86991. };
  86992. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86993. this._prepareRessources();
  86994. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86995. return;
  86996. }
  86997. var engine = this._scene.getEngine();
  86998. engine.setDepthWrite(false);
  86999. engine.setColorWrite(false);
  87000. this._colorShader._preBind();
  87001. var boundingBox = mesh._boundingInfo.boundingBox;
  87002. var min = boundingBox.minimum;
  87003. var max = boundingBox.maximum;
  87004. var diff = max.subtract(min);
  87005. var median = min.add(diff.scale(0.5));
  87006. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87007. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87008. .multiply(boundingBox.getWorldMatrix());
  87009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87010. engine.setDepthFunctionToLess();
  87011. this._scene.resetCachedMaterial();
  87012. this._colorShader.bind(worldMatrix);
  87013. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87014. this._colorShader.unbind();
  87015. engine.setDepthFunctionToLessOrEqual();
  87016. engine.setDepthWrite(true);
  87017. engine.setColorWrite(true);
  87018. };
  87019. BoundingBoxRenderer.prototype.dispose = function () {
  87020. if (!this._colorShader) {
  87021. return;
  87022. }
  87023. this.renderList.dispose();
  87024. this._colorShader.dispose();
  87025. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87026. if (buffer) {
  87027. buffer.dispose();
  87028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87029. }
  87030. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87031. };
  87032. return BoundingBoxRenderer;
  87033. }());
  87034. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87035. })(BABYLON || (BABYLON = {}));
  87036. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87037. var BABYLON;
  87038. (function (BABYLON) {
  87039. /**
  87040. * Renders a layer on top of an existing scene
  87041. */
  87042. var UtilityLayerRenderer = /** @class */ (function () {
  87043. /**
  87044. * Instantiates a UtilityLayerRenderer
  87045. * @param originalScene the original scene that will be rendered on top of
  87046. */
  87047. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87048. var _this = this;
  87049. this.originalScene = originalScene;
  87050. this._pointerCaptures = {};
  87051. this._lastPointerEvents = {};
  87052. /**
  87053. * If the utility layer should automatically be rendered on top of existing scene
  87054. */
  87055. this.shouldRender = true;
  87056. /**
  87057. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87058. */
  87059. this.onlyCheckPointerDownEvents = true;
  87060. /**
  87061. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87062. */
  87063. this.processAllEvents = false;
  87064. /**
  87065. * Observable raised when the pointer move from the utility layer scene to the main scene
  87066. */
  87067. this.onPointerOutObservable = new BABYLON.Observable();
  87068. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87069. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87070. originalScene.getEngine().scenes.pop();
  87071. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87072. this.utilityLayerScene.detachControl();
  87073. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87074. if (!_this.processAllEvents) {
  87075. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87076. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87077. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87078. return;
  87079. }
  87080. }
  87081. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87082. if (!prePointerInfo.ray && utilityScenePick) {
  87083. prePointerInfo.ray = utilityScenePick.ray;
  87084. }
  87085. // always fire the prepointer oversvable
  87086. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87087. // allow every non pointer down event to flow to the utility layer
  87088. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87089. if (!prePointerInfo.skipOnPointerObservable) {
  87090. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87091. }
  87092. return;
  87093. }
  87094. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87095. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87096. if (utilityScenePick && utilityScenePick.hit) {
  87097. if (!prePointerInfo.skipOnPointerObservable) {
  87098. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87099. }
  87100. prePointerInfo.skipOnPointerObservable = true;
  87101. }
  87102. }
  87103. else {
  87104. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87105. var pointerEvent = (prePointerInfo.event);
  87106. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87107. if (originalScenePick && utilityScenePick) {
  87108. if (utilityScenePick.distance === 0) {
  87109. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87110. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87111. }
  87112. }
  87113. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87114. if (!prePointerInfo.skipOnPointerObservable) {
  87115. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87116. _this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87117. }
  87118. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87119. }
  87120. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87121. // We need to send a last pointup to the utilityLayerScene to make sure animations can complete
  87122. if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87123. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87124. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87125. }
  87126. }
  87127. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87128. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87129. }
  87130. }
  87131. }
  87132. });
  87133. // Render directly on top of existing scene without clearing
  87134. this.utilityLayerScene.autoClear = false;
  87135. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87136. if (_this.shouldRender) {
  87137. _this.render();
  87138. }
  87139. });
  87140. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87141. _this.dispose();
  87142. });
  87143. this._updateCamera();
  87144. }
  87145. /**
  87146. * Renders the utility layers scene on top of the original scene
  87147. */
  87148. UtilityLayerRenderer.prototype.render = function () {
  87149. this._updateCamera();
  87150. this.utilityLayerScene.render(false);
  87151. };
  87152. /**
  87153. * Disposes of the renderer
  87154. */
  87155. UtilityLayerRenderer.prototype.dispose = function () {
  87156. this.onPointerOutObservable.clear();
  87157. if (this._afterRenderObserver) {
  87158. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87159. }
  87160. if (this._sceneDisposeObserver) {
  87161. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87162. }
  87163. if (this._originalPointerObserver) {
  87164. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87165. }
  87166. this.utilityLayerScene.dispose();
  87167. };
  87168. UtilityLayerRenderer.prototype._updateCamera = function () {
  87169. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87170. };
  87171. return UtilityLayerRenderer;
  87172. }());
  87173. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87174. })(BABYLON || (BABYLON = {}));
  87175. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87176. var BABYLON;
  87177. (function (BABYLON) {
  87178. /**
  87179. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87180. */
  87181. var PointerDragBehavior = /** @class */ (function () {
  87182. /**
  87183. * Creates a pointer drag behavior that can be attached to a mesh
  87184. * @param options The drag axis or normal of the plane that will be dragged across.
  87185. */
  87186. function PointerDragBehavior(options) {
  87187. this.options = options;
  87188. this._draggingID = -1;
  87189. /**
  87190. * Fires each time the attached mesh is dragged with the pointer
  87191. */
  87192. this.onDragObservable = new BABYLON.Observable();
  87193. /**
  87194. * Fires each time a drag begins (eg. mouse down on mesh)
  87195. */
  87196. this.onDragStartObservable = new BABYLON.Observable();
  87197. /**
  87198. * Fires each time a drag ends (eg. mouse release after drag)
  87199. */
  87200. this.onDragEndObservable = new BABYLON.Observable();
  87201. /**
  87202. * If the attached mesh should be moved when dragged
  87203. */
  87204. this.moveAttached = true;
  87205. /**
  87206. * Mesh with the position where the drag plane should be placed
  87207. */
  87208. this._dragPlaneParent = null;
  87209. /**
  87210. * If the drag behavior will react to drag events
  87211. */
  87212. this.enabled = true;
  87213. var optionCount = 0;
  87214. if (options.dragAxis) {
  87215. optionCount++;
  87216. }
  87217. if (options.dragPlaneNormal) {
  87218. optionCount++;
  87219. }
  87220. if (optionCount > 1) {
  87221. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87222. }
  87223. if (optionCount < 1) {
  87224. throw "At least one drag mode option must be specified";
  87225. }
  87226. }
  87227. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87228. /**
  87229. * The name of the behavior
  87230. */
  87231. get: function () {
  87232. return "PointerDrag";
  87233. },
  87234. enumerable: true,
  87235. configurable: true
  87236. });
  87237. /**
  87238. * Initializes the behavior
  87239. */
  87240. PointerDragBehavior.prototype.init = function () { };
  87241. /**
  87242. * Attaches the drag behavior the passed in mesh
  87243. * @param ownerNode The mesh that will be dragged around once attached
  87244. */
  87245. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87246. var _this = this;
  87247. this._scene = ownerNode.getScene();
  87248. this._attachedNode = ownerNode;
  87249. // Initialize drag plane to not interfere with existing scene
  87250. if (!PointerDragBehavior._planeScene) {
  87251. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87252. this._scene.getEngine().scenes.pop();
  87253. }
  87254. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87255. // State of the drag
  87256. var dragging = false;
  87257. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87258. var delta = new BABYLON.Vector3(0, 0, 0);
  87259. var pickPredicate = function (m) {
  87260. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87261. };
  87262. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87263. if (!_this.enabled) {
  87264. return;
  87265. }
  87266. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87267. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87268. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87269. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87270. if (pickedPoint) {
  87271. dragging = true;
  87272. _this._draggingID = pointerInfo.event.pointerId;
  87273. lastPosition.copyFrom(pickedPoint);
  87274. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87275. }
  87276. }
  87277. }
  87278. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87279. if (_this._draggingID == pointerInfo.event.pointerId) {
  87280. dragging = false;
  87281. _this._draggingID = -1;
  87282. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87283. }
  87284. }
  87285. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87286. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87287. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87288. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87289. if (pickedPoint) {
  87290. // depending on the drag mode option drag accordingly
  87291. if (_this.options.dragAxis) {
  87292. //get the closest point on the dragaxis from the selected mesh to the picked point location
  87293. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  87294. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  87295. }
  87296. else {
  87297. pickedPoint.subtractToRef(lastPosition, delta);
  87298. }
  87299. if (_this.moveAttached) {
  87300. _this._attachedNode.position.addInPlace(delta);
  87301. }
  87302. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  87303. lastPosition.copyFrom(pickedPoint);
  87304. }
  87305. }
  87306. }
  87307. });
  87308. };
  87309. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87310. var _this = this;
  87311. if (!ray) {
  87312. return null;
  87313. }
  87314. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87315. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87316. return pickResult.pickedPoint;
  87317. }
  87318. else {
  87319. return null;
  87320. }
  87321. };
  87322. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87323. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87324. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  87325. if (this.options.dragAxis) {
  87326. var camPos = ray.origin;
  87327. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87328. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  87329. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  87330. // Get perpendicular line from direction to camera and drag axis
  87331. var lineA = pointB.subtract(pointA);
  87332. var lineB = pointC.subtract(pointA);
  87333. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87334. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87335. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87336. this._dragPlane.position.copyFrom(pointA);
  87337. this._dragPlane.lookAt(pointA.add(norm));
  87338. }
  87339. else if (this.options.dragPlaneNormal) {
  87340. this._dragPlane.position.copyFrom(pointA);
  87341. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  87342. }
  87343. this._dragPlane.computeWorldMatrix(true);
  87344. };
  87345. /**
  87346. * Detaches the behavior from the mesh
  87347. */
  87348. PointerDragBehavior.prototype.detach = function () {
  87349. if (this._pointerObserver) {
  87350. this._scene.onPointerObservable.remove(this._pointerObserver);
  87351. }
  87352. };
  87353. return PointerDragBehavior;
  87354. }());
  87355. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87356. })(BABYLON || (BABYLON = {}));
  87357. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87358. var BABYLON;
  87359. (function (BABYLON) {
  87360. /**
  87361. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87362. */
  87363. var Gizmo = /** @class */ (function () {
  87364. /**
  87365. * Creates a gizmo
  87366. * @param gizmoLayer The utility layer the gizmo will be added to
  87367. */
  87368. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87369. var _this = this;
  87370. this.gizmoLayer = gizmoLayer;
  87371. this._interactionsEnabled = true;
  87372. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87373. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87374. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87375. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87376. _this._rootMesh.scaling.set(dist, dist, dist);
  87377. }
  87378. if (_this.attachedMesh) {
  87379. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87380. }
  87381. });
  87382. }
  87383. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87384. };
  87385. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87386. get: function () {
  87387. return this._interactionsEnabled;
  87388. },
  87389. /**
  87390. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87391. */
  87392. set: function (value) {
  87393. this._interactionsEnabled = value;
  87394. this._onInteractionsEnabledChanged(value);
  87395. },
  87396. enumerable: true,
  87397. configurable: true
  87398. });
  87399. /**
  87400. * Disposes of the gizmo
  87401. */
  87402. Gizmo.prototype.dispose = function () {
  87403. this._rootMesh.dispose();
  87404. if (this._beforeRenderObserver) {
  87405. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87406. }
  87407. };
  87408. return Gizmo;
  87409. }());
  87410. BABYLON.Gizmo = Gizmo;
  87411. })(BABYLON || (BABYLON = {}));
  87412. //# sourceMappingURL=babylon.gizmo.js.map
  87413. var BABYLON;
  87414. (function (BABYLON) {
  87415. /**
  87416. * Single axis drag gizmo
  87417. */
  87418. var AxisDragGizmo = /** @class */ (function (_super) {
  87419. __extends(AxisDragGizmo, _super);
  87420. /**
  87421. * Creates an AxisDragGizmo
  87422. * @param gizmoLayer The utility layer the gizmo will be added to
  87423. * @param dragAxis The axis which the gizmo will be able to drag on
  87424. * @param color The color of the gizmo
  87425. */
  87426. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87427. var _this = _super.call(this, gizmoLayer) || this;
  87428. // Create Material
  87429. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87430. coloredMaterial.disableLighting = true;
  87431. coloredMaterial.emissiveColor = color;
  87432. // Build mesh on root node
  87433. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87434. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87435. _this._rootMesh.addChild(arrowMesh);
  87436. _this._rootMesh.addChild(arrowTail);
  87437. // Position arrow pointing in its drag axis
  87438. arrowMesh.scaling.scaleInPlace(0.1);
  87439. arrowMesh.material = coloredMaterial;
  87440. arrowMesh.rotation.x = Math.PI / 2;
  87441. arrowMesh.position.z += 0.3;
  87442. arrowTail.rotation.x = Math.PI / 2;
  87443. arrowTail.material = coloredMaterial;
  87444. arrowTail.position.z += 0.2;
  87445. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87446. // Add drag behavior to handle events when the gizmo is dragged
  87447. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87448. _this._dragBehavior.moveAttached = false;
  87449. _this._rootMesh.addBehavior(_this._dragBehavior);
  87450. _this._dragBehavior.onDragObservable.add(function (event) {
  87451. if (!_this.interactionsEnabled) {
  87452. return;
  87453. }
  87454. if (_this.attachedMesh) {
  87455. _this.attachedMesh.position.addInPlace(event.delta);
  87456. }
  87457. });
  87458. return _this;
  87459. }
  87460. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87461. this._dragBehavior.enabled = value;
  87462. };
  87463. /**
  87464. * Disposes of the gizmo
  87465. */
  87466. AxisDragGizmo.prototype.dispose = function () {
  87467. this._dragBehavior.detach();
  87468. _super.prototype.dispose.call(this);
  87469. };
  87470. return AxisDragGizmo;
  87471. }(BABYLON.Gizmo));
  87472. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87473. })(BABYLON || (BABYLON = {}));
  87474. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87475. var BABYLON;
  87476. (function (BABYLON) {
  87477. /**
  87478. * Single axis scale gizmo
  87479. */
  87480. var AxisScaleGizmo = /** @class */ (function (_super) {
  87481. __extends(AxisScaleGizmo, _super);
  87482. /**
  87483. * Creates an AxisScaleGizmo
  87484. * @param gizmoLayer The utility layer the gizmo will be added to
  87485. * @param dragAxis The axis which the gizmo will be able to scale on
  87486. * @param color The color of the gizmo
  87487. */
  87488. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87489. var _this = _super.call(this, gizmoLayer) || this;
  87490. // Create Material
  87491. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87492. coloredMaterial.disableLighting = true;
  87493. coloredMaterial.emissiveColor = color;
  87494. // Build mesh on root node
  87495. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87496. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87497. _this._rootMesh.addChild(arrowMesh);
  87498. _this._rootMesh.addChild(arrowTail);
  87499. // Position arrow pointing in its drag axis
  87500. arrowMesh.scaling.scaleInPlace(0.1);
  87501. arrowMesh.material = coloredMaterial;
  87502. arrowMesh.rotation.x = Math.PI / 2;
  87503. arrowMesh.position.z += 0.3;
  87504. arrowTail.rotation.x = Math.PI / 2;
  87505. arrowTail.material = coloredMaterial;
  87506. arrowTail.position.z += 0.2;
  87507. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87508. // Add drag behavior to handle events when the gizmo is dragged
  87509. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87510. _this._dragBehavior.moveAttached = false;
  87511. _this._rootMesh.addBehavior(_this._dragBehavior);
  87512. _this._dragBehavior.onDragObservable.add(function (event) {
  87513. if (!_this.interactionsEnabled) {
  87514. return;
  87515. }
  87516. if (_this.attachedMesh) {
  87517. _this.attachedMesh.scaling.addInPlace(event.delta);
  87518. }
  87519. });
  87520. return _this;
  87521. }
  87522. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87523. this._dragBehavior.enabled = value;
  87524. };
  87525. /**
  87526. * Disposes of the gizmo
  87527. */
  87528. AxisScaleGizmo.prototype.dispose = function () {
  87529. this._dragBehavior.detach();
  87530. _super.prototype.dispose.call(this);
  87531. };
  87532. return AxisScaleGizmo;
  87533. }(BABYLON.Gizmo));
  87534. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87535. })(BABYLON || (BABYLON = {}));
  87536. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87537. var BABYLON;
  87538. (function (BABYLON) {
  87539. /**
  87540. * Single plane rotation gizmo
  87541. */
  87542. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87543. __extends(PlaneRotationGizmo, _super);
  87544. /**
  87545. * Creates a PlaneRotationGizmo
  87546. * @param gizmoLayer The utility layer the gizmo will be added to
  87547. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87548. * @param color The color of the gizmo
  87549. */
  87550. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87551. var _this = _super.call(this, gizmoLayer) || this;
  87552. // Create Material
  87553. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87554. coloredMaterial.disableLighting = true;
  87555. coloredMaterial.emissiveColor = color;
  87556. // Build mesh on root node
  87557. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87558. _this._rootMesh.addChild(rotationMesh);
  87559. // Position arrow pointing in its drag axis
  87560. rotationMesh.scaling.scaleInPlace(0.1);
  87561. rotationMesh.material = coloredMaterial;
  87562. rotationMesh.rotation.x = Math.PI / 2;
  87563. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87564. // Add drag behavior to handle events when the gizmo is dragged
  87565. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87566. _this._dragBehavior.moveAttached = false;
  87567. _this._rootMesh.addBehavior(_this._dragBehavior);
  87568. var lastDragPosition = null;
  87569. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87570. if (!_this.interactionsEnabled) {
  87571. return;
  87572. }
  87573. lastDragPosition = e.dragPlanePoint;
  87574. });
  87575. _this._dragBehavior.onDragObservable.add(function (event) {
  87576. if (!_this.interactionsEnabled) {
  87577. return;
  87578. }
  87579. if (_this.attachedMesh && lastDragPosition) {
  87580. if (!_this.attachedMesh.rotationQuaternion) {
  87581. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87582. }
  87583. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87584. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87585. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87586. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87587. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87588. var angle = Math.atan2(cross.length(), dot);
  87589. var up = planeNormal.clone();
  87590. // Flip up vector depending on which side the camera is on
  87591. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87592. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87593. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87594. up.scaleInPlace(-1);
  87595. }
  87596. }
  87597. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87598. if (halfCircleSide)
  87599. angle = -angle;
  87600. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87601. var quaternionCoefficient = Math.sin(angle / 2);
  87602. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87603. // Rotate selected mesh quaternion over fixed axis
  87604. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87605. lastDragPosition = event.dragPlanePoint;
  87606. }
  87607. });
  87608. return _this;
  87609. }
  87610. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87611. this._dragBehavior.enabled = value;
  87612. };
  87613. /**
  87614. * Disposes of the gizmo
  87615. */
  87616. PlaneRotationGizmo.prototype.dispose = function () {
  87617. this._dragBehavior.detach();
  87618. _super.prototype.dispose.call(this);
  87619. };
  87620. return PlaneRotationGizmo;
  87621. }(BABYLON.Gizmo));
  87622. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87623. })(BABYLON || (BABYLON = {}));
  87624. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87625. var BABYLON;
  87626. (function (BABYLON) {
  87627. /**
  87628. * Gizmo that enables dragging a mesh along 3 axis
  87629. */
  87630. var PositionGizmo = /** @class */ (function (_super) {
  87631. __extends(PositionGizmo, _super);
  87632. /**
  87633. * Creates a PositionGizmo
  87634. * @param gizmoLayer The utility layer the gizmo will be added to
  87635. */
  87636. function PositionGizmo(gizmoLayer) {
  87637. var _this = _super.call(this, gizmoLayer) || this;
  87638. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87639. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87640. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87641. return _this;
  87642. }
  87643. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87644. set: function (mesh) {
  87645. this._xDrag.attachedMesh = mesh;
  87646. this._yDrag.attachedMesh = mesh;
  87647. this._zDrag.attachedMesh = mesh;
  87648. },
  87649. enumerable: true,
  87650. configurable: true
  87651. });
  87652. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87653. this._xDrag.interactionsEnabled = value;
  87654. this._yDrag.interactionsEnabled = value;
  87655. this._zDrag.interactionsEnabled = value;
  87656. };
  87657. /**
  87658. * Disposes of the gizmo
  87659. */
  87660. PositionGizmo.prototype.dispose = function () {
  87661. this._xDrag.dispose();
  87662. this._yDrag.dispose();
  87663. this._zDrag.dispose();
  87664. };
  87665. return PositionGizmo;
  87666. }(BABYLON.Gizmo));
  87667. BABYLON.PositionGizmo = PositionGizmo;
  87668. })(BABYLON || (BABYLON = {}));
  87669. //# sourceMappingURL=babylon.positionGizmo.js.map
  87670. var BABYLON;
  87671. (function (BABYLON) {
  87672. /**
  87673. * Gizmo that enables rotating a mesh along 3 axis
  87674. */
  87675. var RotationGizmo = /** @class */ (function (_super) {
  87676. __extends(RotationGizmo, _super);
  87677. /**
  87678. * Creates a RotationGizmo
  87679. * @param gizmoLayer The utility layer the gizmo will be added to
  87680. */
  87681. function RotationGizmo(gizmoLayer) {
  87682. var _this = _super.call(this, gizmoLayer) || this;
  87683. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87684. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87685. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87686. return _this;
  87687. }
  87688. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87689. set: function (mesh) {
  87690. this._xDrag.attachedMesh = mesh;
  87691. this._yDrag.attachedMesh = mesh;
  87692. this._zDrag.attachedMesh = mesh;
  87693. },
  87694. enumerable: true,
  87695. configurable: true
  87696. });
  87697. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87698. this._xDrag.interactionsEnabled = value;
  87699. this._yDrag.interactionsEnabled = value;
  87700. this._zDrag.interactionsEnabled = value;
  87701. };
  87702. /**
  87703. * Disposes of the gizmo
  87704. */
  87705. RotationGizmo.prototype.dispose = function () {
  87706. this._xDrag.dispose();
  87707. this._yDrag.dispose();
  87708. this._zDrag.dispose();
  87709. };
  87710. return RotationGizmo;
  87711. }(BABYLON.Gizmo));
  87712. BABYLON.RotationGizmo = RotationGizmo;
  87713. })(BABYLON || (BABYLON = {}));
  87714. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87715. var BABYLON;
  87716. (function (BABYLON) {
  87717. /**
  87718. * Gizmo that enables scaling a mesh along 3 axis
  87719. */
  87720. var ScaleGizmo = /** @class */ (function (_super) {
  87721. __extends(ScaleGizmo, _super);
  87722. /**
  87723. * Creates a ScaleGizmo
  87724. * @param gizmoLayer The utility layer the gizmo will be added to
  87725. */
  87726. function ScaleGizmo(gizmoLayer) {
  87727. var _this = _super.call(this, gizmoLayer) || this;
  87728. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87729. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87730. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87731. return _this;
  87732. }
  87733. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87734. set: function (mesh) {
  87735. this._xDrag.attachedMesh = mesh;
  87736. this._yDrag.attachedMesh = mesh;
  87737. this._zDrag.attachedMesh = mesh;
  87738. },
  87739. enumerable: true,
  87740. configurable: true
  87741. });
  87742. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87743. this._xDrag.interactionsEnabled = value;
  87744. this._yDrag.interactionsEnabled = value;
  87745. this._zDrag.interactionsEnabled = value;
  87746. };
  87747. /**
  87748. * Disposes of the gizmo
  87749. */
  87750. ScaleGizmo.prototype.dispose = function () {
  87751. this._xDrag.dispose();
  87752. this._yDrag.dispose();
  87753. this._zDrag.dispose();
  87754. };
  87755. return ScaleGizmo;
  87756. }(BABYLON.Gizmo));
  87757. BABYLON.ScaleGizmo = ScaleGizmo;
  87758. })(BABYLON || (BABYLON = {}));
  87759. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87760. var BABYLON;
  87761. (function (BABYLON) {
  87762. /**
  87763. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  87764. */
  87765. var GizmoManager = /** @class */ (function () {
  87766. /**
  87767. * Instatiates a gizmo manager
  87768. * @param scene the scene to overlay the gizmos on top of
  87769. * @param options If only a single gizmo should exist at one time
  87770. */
  87771. function GizmoManager(scene, options) {
  87772. var _this = this;
  87773. this.scene = scene;
  87774. // Set of gizmos that are currently in the scene for each mesh
  87775. this._gizmoSet = {};
  87776. this._pointerObserver = null;
  87777. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  87778. // Options parsing
  87779. if (!options) {
  87780. options = {};
  87781. }
  87782. if (options.singleGizmo === undefined) {
  87783. options.singleGizmo = true;
  87784. }
  87785. // Instatiate/dispose gizmos based on pointer actions
  87786. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  87787. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87788. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  87789. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  87790. if (options.singleGizmo) {
  87791. _this._clearGizmos();
  87792. }
  87793. // Enable gizmo when mesh is selected
  87794. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  87795. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87796. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87797. }
  87798. else {
  87799. if (!options.singleGizmo) {
  87800. // Disable gizmo when clicked again
  87801. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  87802. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  87803. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  87804. }
  87805. }
  87806. }
  87807. else {
  87808. if (options.singleGizmo) {
  87809. // Disable gizmo when clicked away
  87810. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87811. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  87812. if (gizmoPick && !gizmoPick.hit) {
  87813. _this._clearGizmos();
  87814. }
  87815. }
  87816. }
  87817. }
  87818. }
  87819. });
  87820. }
  87821. /**
  87822. * Disposes of the gizmo manager
  87823. */
  87824. GizmoManager.prototype.dispose = function () {
  87825. this.scene.onPointerObservable.remove(this._pointerObserver);
  87826. this._clearGizmos();
  87827. this._gizmoLayer.dispose();
  87828. };
  87829. GizmoManager.prototype._clearGizmos = function () {
  87830. for (var key in this._gizmoSet) {
  87831. if (this._gizmoSet.hasOwnProperty(key)) {
  87832. this._gizmoSet[key].positionGizmo.dispose();
  87833. this._gizmoSet[key].rotationGizmo.dispose();
  87834. delete this._gizmoSet[key];
  87835. }
  87836. }
  87837. };
  87838. return GizmoManager;
  87839. }());
  87840. BABYLON.GizmoManager = GizmoManager;
  87841. })(BABYLON || (BABYLON = {}));
  87842. //# sourceMappingURL=babylon.gizmoManager.js.map
  87843. var BABYLON;
  87844. (function (BABYLON) {
  87845. /**
  87846. * Defines a target to use with MorphTargetManager
  87847. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87848. */
  87849. var MorphTarget = /** @class */ (function () {
  87850. /**
  87851. * Creates a new MorphTarget
  87852. * @param name defines the name of the target
  87853. * @param influence defines the influence to use
  87854. */
  87855. function MorphTarget(
  87856. /** defines the name of the target */
  87857. name, influence, scene) {
  87858. if (influence === void 0) { influence = 0; }
  87859. if (scene === void 0) { scene = null; }
  87860. this.name = name;
  87861. /**
  87862. * Gets or sets the list of animations
  87863. */
  87864. this.animations = new Array();
  87865. this._positions = null;
  87866. this._normals = null;
  87867. this._tangents = null;
  87868. /**
  87869. * Observable raised when the influence changes
  87870. */
  87871. this.onInfluenceChanged = new BABYLON.Observable();
  87872. this._animationPropertiesOverride = null;
  87873. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87874. this.influence = influence;
  87875. }
  87876. Object.defineProperty(MorphTarget.prototype, "influence", {
  87877. /**
  87878. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  87879. */
  87880. get: function () {
  87881. return this._influence;
  87882. },
  87883. set: function (influence) {
  87884. if (this._influence === influence) {
  87885. return;
  87886. }
  87887. var previous = this._influence;
  87888. this._influence = influence;
  87889. if (this.onInfluenceChanged.hasObservers) {
  87890. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  87891. }
  87892. },
  87893. enumerable: true,
  87894. configurable: true
  87895. });
  87896. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  87897. /**
  87898. * Gets or sets the animation properties override
  87899. */
  87900. get: function () {
  87901. if (!this._animationPropertiesOverride && this._scene) {
  87902. return this._scene.animationPropertiesOverride;
  87903. }
  87904. return this._animationPropertiesOverride;
  87905. },
  87906. set: function (value) {
  87907. this._animationPropertiesOverride = value;
  87908. },
  87909. enumerable: true,
  87910. configurable: true
  87911. });
  87912. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  87913. /**
  87914. * Gets a boolean defining if the target contains position data
  87915. */
  87916. get: function () {
  87917. return !!this._positions;
  87918. },
  87919. enumerable: true,
  87920. configurable: true
  87921. });
  87922. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  87923. /**
  87924. * Gets a boolean defining if the target contains normal data
  87925. */
  87926. get: function () {
  87927. return !!this._normals;
  87928. },
  87929. enumerable: true,
  87930. configurable: true
  87931. });
  87932. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  87933. /**
  87934. * Gets a boolean defining if the target contains tangent data
  87935. */
  87936. get: function () {
  87937. return !!this._tangents;
  87938. },
  87939. enumerable: true,
  87940. configurable: true
  87941. });
  87942. /**
  87943. * Affects position data to this target
  87944. * @param data defines the position data to use
  87945. */
  87946. MorphTarget.prototype.setPositions = function (data) {
  87947. this._positions = data;
  87948. };
  87949. /**
  87950. * Gets the position data stored in this target
  87951. * @returns a FloatArray containing the position data (or null if not present)
  87952. */
  87953. MorphTarget.prototype.getPositions = function () {
  87954. return this._positions;
  87955. };
  87956. /**
  87957. * Affects normal data to this target
  87958. * @param data defines the normal data to use
  87959. */
  87960. MorphTarget.prototype.setNormals = function (data) {
  87961. this._normals = data;
  87962. };
  87963. /**
  87964. * Gets the normal data stored in this target
  87965. * @returns a FloatArray containing the normal data (or null if not present)
  87966. */
  87967. MorphTarget.prototype.getNormals = function () {
  87968. return this._normals;
  87969. };
  87970. /**
  87971. * Affects tangent data to this target
  87972. * @param data defines the tangent data to use
  87973. */
  87974. MorphTarget.prototype.setTangents = function (data) {
  87975. this._tangents = data;
  87976. };
  87977. /**
  87978. * Gets the tangent data stored in this target
  87979. * @returns a FloatArray containing the tangent data (or null if not present)
  87980. */
  87981. MorphTarget.prototype.getTangents = function () {
  87982. return this._tangents;
  87983. };
  87984. /**
  87985. * Serializes the current target into a Serialization object
  87986. * @returns the serialized object
  87987. */
  87988. MorphTarget.prototype.serialize = function () {
  87989. var serializationObject = {};
  87990. serializationObject.name = this.name;
  87991. serializationObject.influence = this.influence;
  87992. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  87993. if (this.hasNormals) {
  87994. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  87995. }
  87996. if (this.hasTangents) {
  87997. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  87998. }
  87999. // Animations
  88000. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  88001. return serializationObject;
  88002. };
  88003. // Statics
  88004. /**
  88005. * Creates a new target from serialized data
  88006. * @param serializationObject defines the serialized data to use
  88007. * @returns a new MorphTarget
  88008. */
  88009. MorphTarget.Parse = function (serializationObject) {
  88010. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  88011. result.setPositions(serializationObject.positions);
  88012. if (serializationObject.normals) {
  88013. result.setNormals(serializationObject.normals);
  88014. }
  88015. if (serializationObject.tangents) {
  88016. result.setTangents(serializationObject.tangents);
  88017. }
  88018. // Animations
  88019. if (serializationObject.animations) {
  88020. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  88021. var parsedAnimation = serializationObject.animations[animationIndex];
  88022. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  88023. }
  88024. }
  88025. return result;
  88026. };
  88027. /**
  88028. * Creates a MorphTarget from mesh data
  88029. * @param mesh defines the source mesh
  88030. * @param name defines the name to use for the new target
  88031. * @param influence defines the influence to attach to the target
  88032. * @returns a new MorphTarget
  88033. */
  88034. MorphTarget.FromMesh = function (mesh, name, influence) {
  88035. if (!name) {
  88036. name = mesh.name;
  88037. }
  88038. var result = new MorphTarget(name, influence, mesh.getScene());
  88039. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88040. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88041. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  88042. }
  88043. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  88044. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  88045. }
  88046. return result;
  88047. };
  88048. return MorphTarget;
  88049. }());
  88050. BABYLON.MorphTarget = MorphTarget;
  88051. })(BABYLON || (BABYLON = {}));
  88052. //# sourceMappingURL=babylon.morphTarget.js.map
  88053. var BABYLON;
  88054. (function (BABYLON) {
  88055. /**
  88056. * This class is used to deform meshes using morphing between different targets
  88057. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88058. */
  88059. var MorphTargetManager = /** @class */ (function () {
  88060. /**
  88061. * Creates a new MorphTargetManager
  88062. * @param scene defines the current scene
  88063. */
  88064. function MorphTargetManager(scene) {
  88065. if (scene === void 0) { scene = null; }
  88066. this._targets = new Array();
  88067. this._targetObservable = new Array();
  88068. this._activeTargets = new BABYLON.SmartArray(16);
  88069. this._supportsNormals = false;
  88070. this._supportsTangents = false;
  88071. this._vertexCount = 0;
  88072. this._uniqueId = 0;
  88073. this._tempInfluences = new Array();
  88074. if (!scene) {
  88075. scene = BABYLON.Engine.LastCreatedScene;
  88076. }
  88077. this._scene = scene;
  88078. if (this._scene) {
  88079. this._scene.morphTargetManagers.push(this);
  88080. this._uniqueId = this._scene.getUniqueId();
  88081. }
  88082. }
  88083. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  88084. /**
  88085. * Gets the unique ID of this manager
  88086. */
  88087. get: function () {
  88088. return this._uniqueId;
  88089. },
  88090. enumerable: true,
  88091. configurable: true
  88092. });
  88093. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  88094. /**
  88095. * Gets the number of vertices handled by this manager
  88096. */
  88097. get: function () {
  88098. return this._vertexCount;
  88099. },
  88100. enumerable: true,
  88101. configurable: true
  88102. });
  88103. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  88104. /**
  88105. * Gets a boolean indicating if this manager supports morphing of normals
  88106. */
  88107. get: function () {
  88108. return this._supportsNormals;
  88109. },
  88110. enumerable: true,
  88111. configurable: true
  88112. });
  88113. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88114. /**
  88115. * Gets a boolean indicating if this manager supports morphing of tangents
  88116. */
  88117. get: function () {
  88118. return this._supportsTangents;
  88119. },
  88120. enumerable: true,
  88121. configurable: true
  88122. });
  88123. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88124. /**
  88125. * Gets the number of targets stored in this manager
  88126. */
  88127. get: function () {
  88128. return this._targets.length;
  88129. },
  88130. enumerable: true,
  88131. configurable: true
  88132. });
  88133. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88134. /**
  88135. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88136. */
  88137. get: function () {
  88138. return this._activeTargets.length;
  88139. },
  88140. enumerable: true,
  88141. configurable: true
  88142. });
  88143. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88144. /**
  88145. * Gets the list of influences (one per target)
  88146. */
  88147. get: function () {
  88148. return this._influences;
  88149. },
  88150. enumerable: true,
  88151. configurable: true
  88152. });
  88153. /**
  88154. * Gets the active target at specified index. An active target is a target with an influence > 0
  88155. * @param index defines the index to check
  88156. * @returns the requested target
  88157. */
  88158. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88159. return this._activeTargets.data[index];
  88160. };
  88161. /**
  88162. * Gets the target at specified index
  88163. * @param index defines the index to check
  88164. * @returns the requested target
  88165. */
  88166. MorphTargetManager.prototype.getTarget = function (index) {
  88167. return this._targets[index];
  88168. };
  88169. /**
  88170. * Add a new target to this manager
  88171. * @param target defines the target to add
  88172. */
  88173. MorphTargetManager.prototype.addTarget = function (target) {
  88174. var _this = this;
  88175. this._targets.push(target);
  88176. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88177. _this._syncActiveTargets(needUpdate);
  88178. }));
  88179. this._syncActiveTargets(true);
  88180. };
  88181. /**
  88182. * Removes a target from the manager
  88183. * @param target defines the target to remove
  88184. */
  88185. MorphTargetManager.prototype.removeTarget = function (target) {
  88186. var index = this._targets.indexOf(target);
  88187. if (index >= 0) {
  88188. this._targets.splice(index, 1);
  88189. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88190. this._syncActiveTargets(true);
  88191. }
  88192. };
  88193. /**
  88194. * Serializes the current manager into a Serialization object
  88195. * @returns the serialized object
  88196. */
  88197. MorphTargetManager.prototype.serialize = function () {
  88198. var serializationObject = {};
  88199. serializationObject.id = this.uniqueId;
  88200. serializationObject.targets = [];
  88201. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88202. var target = _a[_i];
  88203. serializationObject.targets.push(target.serialize());
  88204. }
  88205. return serializationObject;
  88206. };
  88207. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88208. var influenceCount = 0;
  88209. this._activeTargets.reset();
  88210. this._supportsNormals = true;
  88211. this._supportsTangents = true;
  88212. this._vertexCount = 0;
  88213. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88214. var target = _a[_i];
  88215. this._activeTargets.push(target);
  88216. this._tempInfluences[influenceCount++] = target.influence;
  88217. var positions = target.getPositions();
  88218. if (positions) {
  88219. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88220. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88221. var vertexCount = positions.length / 3;
  88222. if (this._vertexCount === 0) {
  88223. this._vertexCount = vertexCount;
  88224. }
  88225. else if (this._vertexCount !== vertexCount) {
  88226. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88227. return;
  88228. }
  88229. }
  88230. }
  88231. if (!this._influences || this._influences.length !== influenceCount) {
  88232. this._influences = new Float32Array(influenceCount);
  88233. }
  88234. for (var index = 0; index < influenceCount; index++) {
  88235. this._influences[index] = this._tempInfluences[index];
  88236. }
  88237. if (needUpdate) {
  88238. this.synchronize();
  88239. }
  88240. };
  88241. /**
  88242. * Syncrhonize the targets with all the meshes using this morph target manager
  88243. */
  88244. MorphTargetManager.prototype.synchronize = function () {
  88245. if (!this._scene) {
  88246. return;
  88247. }
  88248. // Flag meshes as dirty to resync with the active targets
  88249. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88250. var mesh = _a[_i];
  88251. if (mesh.morphTargetManager === this) {
  88252. mesh._syncGeometryWithMorphTargetManager();
  88253. }
  88254. }
  88255. };
  88256. // Statics
  88257. /**
  88258. * Creates a new MorphTargetManager from serialized data
  88259. * @param serializationObject defines the serialized data
  88260. * @param scene defines the hosting scene
  88261. * @returns the new MorphTargetManager
  88262. */
  88263. MorphTargetManager.Parse = function (serializationObject, scene) {
  88264. var result = new MorphTargetManager(scene);
  88265. result._uniqueId = serializationObject.id;
  88266. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88267. var targetData = _a[_i];
  88268. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88269. }
  88270. return result;
  88271. };
  88272. return MorphTargetManager;
  88273. }());
  88274. BABYLON.MorphTargetManager = MorphTargetManager;
  88275. })(BABYLON || (BABYLON = {}));
  88276. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88277. var BABYLON;
  88278. (function (BABYLON) {
  88279. var Octree = /** @class */ (function () {
  88280. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88281. if (maxDepth === void 0) { maxDepth = 2; }
  88282. this.maxDepth = maxDepth;
  88283. this.dynamicContent = new Array();
  88284. this._maxBlockCapacity = maxBlockCapacity || 64;
  88285. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88286. this._creationFunc = creationFunc;
  88287. }
  88288. // Methods
  88289. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88290. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88291. };
  88292. Octree.prototype.addMesh = function (entry) {
  88293. for (var index = 0; index < this.blocks.length; index++) {
  88294. var block = this.blocks[index];
  88295. block.addEntry(entry);
  88296. }
  88297. };
  88298. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88299. this._selectionContent.reset();
  88300. for (var index = 0; index < this.blocks.length; index++) {
  88301. var block = this.blocks[index];
  88302. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88303. }
  88304. if (allowDuplicate) {
  88305. this._selectionContent.concat(this.dynamicContent);
  88306. }
  88307. else {
  88308. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88309. }
  88310. return this._selectionContent;
  88311. };
  88312. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88313. this._selectionContent.reset();
  88314. for (var index = 0; index < this.blocks.length; index++) {
  88315. var block = this.blocks[index];
  88316. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88317. }
  88318. if (allowDuplicate) {
  88319. this._selectionContent.concat(this.dynamicContent);
  88320. }
  88321. else {
  88322. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88323. }
  88324. return this._selectionContent;
  88325. };
  88326. Octree.prototype.intersectsRay = function (ray) {
  88327. this._selectionContent.reset();
  88328. for (var index = 0; index < this.blocks.length; index++) {
  88329. var block = this.blocks[index];
  88330. block.intersectsRay(ray, this._selectionContent);
  88331. }
  88332. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88333. return this._selectionContent;
  88334. };
  88335. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88336. target.blocks = new Array();
  88337. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88338. // Segmenting space
  88339. for (var x = 0; x < 2; x++) {
  88340. for (var y = 0; y < 2; y++) {
  88341. for (var z = 0; z < 2; z++) {
  88342. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88343. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88344. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88345. block.addEntries(entries);
  88346. target.blocks.push(block);
  88347. }
  88348. }
  88349. }
  88350. };
  88351. Octree.CreationFuncForMeshes = function (entry, block) {
  88352. var boundingInfo = entry.getBoundingInfo();
  88353. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88354. block.entries.push(entry);
  88355. }
  88356. };
  88357. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88358. var boundingInfo = entry.getBoundingInfo();
  88359. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88360. block.entries.push(entry);
  88361. }
  88362. };
  88363. return Octree;
  88364. }());
  88365. BABYLON.Octree = Octree;
  88366. })(BABYLON || (BABYLON = {}));
  88367. //# sourceMappingURL=babylon.octree.js.map
  88368. var BABYLON;
  88369. (function (BABYLON) {
  88370. var OctreeBlock = /** @class */ (function () {
  88371. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88372. this.entries = new Array();
  88373. this._boundingVectors = new Array();
  88374. this._capacity = capacity;
  88375. this._depth = depth;
  88376. this._maxDepth = maxDepth;
  88377. this._creationFunc = creationFunc;
  88378. this._minPoint = minPoint;
  88379. this._maxPoint = maxPoint;
  88380. this._boundingVectors.push(minPoint.clone());
  88381. this._boundingVectors.push(maxPoint.clone());
  88382. this._boundingVectors.push(minPoint.clone());
  88383. this._boundingVectors[2].x = maxPoint.x;
  88384. this._boundingVectors.push(minPoint.clone());
  88385. this._boundingVectors[3].y = maxPoint.y;
  88386. this._boundingVectors.push(minPoint.clone());
  88387. this._boundingVectors[4].z = maxPoint.z;
  88388. this._boundingVectors.push(maxPoint.clone());
  88389. this._boundingVectors[5].z = minPoint.z;
  88390. this._boundingVectors.push(maxPoint.clone());
  88391. this._boundingVectors[6].x = minPoint.x;
  88392. this._boundingVectors.push(maxPoint.clone());
  88393. this._boundingVectors[7].y = minPoint.y;
  88394. }
  88395. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88396. // Property
  88397. get: function () {
  88398. return this._capacity;
  88399. },
  88400. enumerable: true,
  88401. configurable: true
  88402. });
  88403. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88404. get: function () {
  88405. return this._minPoint;
  88406. },
  88407. enumerable: true,
  88408. configurable: true
  88409. });
  88410. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88411. get: function () {
  88412. return this._maxPoint;
  88413. },
  88414. enumerable: true,
  88415. configurable: true
  88416. });
  88417. // Methods
  88418. OctreeBlock.prototype.addEntry = function (entry) {
  88419. if (this.blocks) {
  88420. for (var index = 0; index < this.blocks.length; index++) {
  88421. var block = this.blocks[index];
  88422. block.addEntry(entry);
  88423. }
  88424. return;
  88425. }
  88426. this._creationFunc(entry, this);
  88427. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88428. this.createInnerBlocks();
  88429. }
  88430. };
  88431. OctreeBlock.prototype.addEntries = function (entries) {
  88432. for (var index = 0; index < entries.length; index++) {
  88433. var mesh = entries[index];
  88434. this.addEntry(mesh);
  88435. }
  88436. };
  88437. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88438. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88439. if (this.blocks) {
  88440. for (var index = 0; index < this.blocks.length; index++) {
  88441. var block = this.blocks[index];
  88442. block.select(frustumPlanes, selection, allowDuplicate);
  88443. }
  88444. return;
  88445. }
  88446. if (allowDuplicate) {
  88447. selection.concat(this.entries);
  88448. }
  88449. else {
  88450. selection.concatWithNoDuplicate(this.entries);
  88451. }
  88452. }
  88453. };
  88454. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88455. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88456. if (this.blocks) {
  88457. for (var index = 0; index < this.blocks.length; index++) {
  88458. var block = this.blocks[index];
  88459. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88460. }
  88461. return;
  88462. }
  88463. if (allowDuplicate) {
  88464. selection.concat(this.entries);
  88465. }
  88466. else {
  88467. selection.concatWithNoDuplicate(this.entries);
  88468. }
  88469. }
  88470. };
  88471. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88472. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88473. if (this.blocks) {
  88474. for (var index = 0; index < this.blocks.length; index++) {
  88475. var block = this.blocks[index];
  88476. block.intersectsRay(ray, selection);
  88477. }
  88478. return;
  88479. }
  88480. selection.concatWithNoDuplicate(this.entries);
  88481. }
  88482. };
  88483. OctreeBlock.prototype.createInnerBlocks = function () {
  88484. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88485. };
  88486. return OctreeBlock;
  88487. }());
  88488. BABYLON.OctreeBlock = OctreeBlock;
  88489. })(BABYLON || (BABYLON = {}));
  88490. //# sourceMappingURL=babylon.octreeBlock.js.map
  88491. var BABYLON;
  88492. (function (BABYLON) {
  88493. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88494. __extends(VRDistortionCorrectionPostProcess, _super);
  88495. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88496. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88497. 'LensCenter',
  88498. 'Scale',
  88499. 'ScaleIn',
  88500. 'HmdWarpParam'
  88501. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88502. _this._isRightEye = isRightEye;
  88503. _this._distortionFactors = vrMetrics.distortionK;
  88504. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88505. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88506. _this.adaptScaleToCurrentViewport = true;
  88507. _this.onSizeChangedObservable.add(function () {
  88508. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88509. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88510. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88511. });
  88512. _this.onApplyObservable.add(function (effect) {
  88513. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88514. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88515. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88516. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88517. });
  88518. return _this;
  88519. }
  88520. return VRDistortionCorrectionPostProcess;
  88521. }(BABYLON.PostProcess));
  88522. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88523. })(BABYLON || (BABYLON = {}));
  88524. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88525. var BABYLON;
  88526. (function (BABYLON) {
  88527. /**
  88528. * Postprocess used to generate anaglyphic rendering
  88529. */
  88530. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88531. __extends(AnaglyphPostProcess, _super);
  88532. /**
  88533. * Creates a new AnaglyphPostProcess
  88534. * @param name defines postprocess name
  88535. * @param options defines creation options or target ratio scale
  88536. * @param rigCameras defines cameras using this postprocess
  88537. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88538. * @param engine defines hosting engine
  88539. * @param reusable defines if the postprocess will be reused multiple times per frame
  88540. */
  88541. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88542. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88543. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88544. _this.onApplyObservable.add(function (effect) {
  88545. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88546. });
  88547. return _this;
  88548. }
  88549. return AnaglyphPostProcess;
  88550. }(BABYLON.PostProcess));
  88551. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88552. })(BABYLON || (BABYLON = {}));
  88553. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88554. var BABYLON;
  88555. (function (BABYLON) {
  88556. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88557. __extends(StereoscopicInterlacePostProcess, _super);
  88558. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88559. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88560. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88561. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88562. _this.onSizeChangedObservable.add(function () {
  88563. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88564. });
  88565. _this.onApplyObservable.add(function (effect) {
  88566. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88567. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88568. });
  88569. return _this;
  88570. }
  88571. return StereoscopicInterlacePostProcess;
  88572. }(BABYLON.PostProcess));
  88573. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88574. })(BABYLON || (BABYLON = {}));
  88575. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88576. var BABYLON;
  88577. (function (BABYLON) {
  88578. /**
  88579. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88580. * Screen rotation is taken into account.
  88581. */
  88582. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88583. function FreeCameraDeviceOrientationInput() {
  88584. var _this = this;
  88585. this._screenOrientationAngle = 0;
  88586. this._screenQuaternion = new BABYLON.Quaternion();
  88587. this._alpha = 0;
  88588. this._beta = 0;
  88589. this._gamma = 0;
  88590. this._orientationChanged = function () {
  88591. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88592. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88593. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88594. };
  88595. this._deviceOrientation = function (evt) {
  88596. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88597. _this._beta = evt.beta !== null ? evt.beta : 0;
  88598. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  88599. };
  88600. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  88601. this._orientationChanged();
  88602. }
  88603. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  88604. get: function () {
  88605. return this._camera;
  88606. },
  88607. set: function (camera) {
  88608. this._camera = camera;
  88609. if (this._camera != null && !this._camera.rotationQuaternion) {
  88610. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  88611. }
  88612. },
  88613. enumerable: true,
  88614. configurable: true
  88615. });
  88616. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88617. window.addEventListener("orientationchange", this._orientationChanged);
  88618. window.addEventListener("deviceorientation", this._deviceOrientation);
  88619. //In certain cases, the attach control is called AFTER orientation was changed,
  88620. //So this is needed.
  88621. this._orientationChanged();
  88622. };
  88623. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  88624. window.removeEventListener("orientationchange", this._orientationChanged);
  88625. window.removeEventListener("deviceorientation", this._deviceOrientation);
  88626. };
  88627. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  88628. //if no device orientation provided, don't update the rotation.
  88629. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  88630. if (!this._alpha)
  88631. return;
  88632. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  88633. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  88634. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  88635. //Mirror on XY Plane
  88636. this._camera.rotationQuaternion.z *= -1;
  88637. this._camera.rotationQuaternion.w *= -1;
  88638. };
  88639. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  88640. return "FreeCameraDeviceOrientationInput";
  88641. };
  88642. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  88643. return "deviceOrientation";
  88644. };
  88645. return FreeCameraDeviceOrientationInput;
  88646. }());
  88647. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  88648. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  88649. })(BABYLON || (BABYLON = {}));
  88650. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  88651. var BABYLON;
  88652. (function (BABYLON) {
  88653. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  88654. function ArcRotateCameraVRDeviceOrientationInput() {
  88655. this.alphaCorrection = 1;
  88656. this.betaCorrection = 1;
  88657. this.gammaCorrection = 1;
  88658. this._alpha = 0;
  88659. this._gamma = 0;
  88660. this._dirty = false;
  88661. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  88662. }
  88663. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88664. this.camera.attachControl(element, noPreventDefault);
  88665. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  88666. };
  88667. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  88668. if (evt.alpha !== null) {
  88669. this._alpha = +evt.alpha | 0;
  88670. }
  88671. if (evt.gamma !== null) {
  88672. this._gamma = +evt.gamma | 0;
  88673. }
  88674. this._dirty = true;
  88675. };
  88676. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  88677. if (this._dirty) {
  88678. this._dirty = false;
  88679. if (this._gamma < 0) {
  88680. this._gamma = 180 + this._gamma;
  88681. }
  88682. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  88683. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  88684. }
  88685. };
  88686. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  88687. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  88688. };
  88689. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  88690. return "ArcRotateCameraVRDeviceOrientationInput";
  88691. };
  88692. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  88693. return "VRDeviceOrientation";
  88694. };
  88695. return ArcRotateCameraVRDeviceOrientationInput;
  88696. }());
  88697. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  88698. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  88699. })(BABYLON || (BABYLON = {}));
  88700. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  88701. var BABYLON;
  88702. (function (BABYLON) {
  88703. var VRCameraMetrics = /** @class */ (function () {
  88704. function VRCameraMetrics() {
  88705. this.compensateDistortion = true;
  88706. }
  88707. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  88708. get: function () {
  88709. return this.hResolution / (2 * this.vResolution);
  88710. },
  88711. enumerable: true,
  88712. configurable: true
  88713. });
  88714. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  88715. get: function () {
  88716. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  88717. },
  88718. enumerable: true,
  88719. configurable: true
  88720. });
  88721. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  88722. get: function () {
  88723. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88724. var h = (4 * meters) / this.hScreenSize;
  88725. return BABYLON.Matrix.Translation(h, 0, 0);
  88726. },
  88727. enumerable: true,
  88728. configurable: true
  88729. });
  88730. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  88731. get: function () {
  88732. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88733. var h = (4 * meters) / this.hScreenSize;
  88734. return BABYLON.Matrix.Translation(-h, 0, 0);
  88735. },
  88736. enumerable: true,
  88737. configurable: true
  88738. });
  88739. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  88740. get: function () {
  88741. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  88742. },
  88743. enumerable: true,
  88744. configurable: true
  88745. });
  88746. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  88747. get: function () {
  88748. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  88749. },
  88750. enumerable: true,
  88751. configurable: true
  88752. });
  88753. VRCameraMetrics.GetDefault = function () {
  88754. var result = new VRCameraMetrics();
  88755. result.hResolution = 1280;
  88756. result.vResolution = 800;
  88757. result.hScreenSize = 0.149759993;
  88758. result.vScreenSize = 0.0935999975;
  88759. result.vScreenCenter = 0.0467999987;
  88760. result.eyeToScreenDistance = 0.0410000011;
  88761. result.lensSeparationDistance = 0.0635000020;
  88762. result.interpupillaryDistance = 0.0640000030;
  88763. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  88764. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  88765. result.postProcessScaleFactor = 1.714605507808412;
  88766. result.lensCenterOffset = 0.151976421;
  88767. return result;
  88768. };
  88769. return VRCameraMetrics;
  88770. }());
  88771. BABYLON.VRCameraMetrics = VRCameraMetrics;
  88772. })(BABYLON || (BABYLON = {}));
  88773. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  88774. var BABYLON;
  88775. (function (BABYLON) {
  88776. /**
  88777. * This represents a WebVR camera.
  88778. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  88779. * @example http://doc.babylonjs.com/how_to/webvr_camera
  88780. */
  88781. var WebVRFreeCamera = /** @class */ (function (_super) {
  88782. __extends(WebVRFreeCamera, _super);
  88783. /**
  88784. * Instantiates a WebVRFreeCamera.
  88785. * @param name The name of the WebVRFreeCamera
  88786. * @param position The starting anchor position for the camera
  88787. * @param scene The scene the camera belongs to
  88788. * @param webVROptions a set of customizable options for the webVRCamera
  88789. */
  88790. function WebVRFreeCamera(name, position, scene, webVROptions) {
  88791. if (webVROptions === void 0) { webVROptions = {}; }
  88792. var _this = _super.call(this, name, position, scene) || this;
  88793. _this.webVROptions = webVROptions;
  88794. /**
  88795. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  88796. */
  88797. _this._vrDevice = null;
  88798. /**
  88799. * The rawPose of the vrDevice.
  88800. */
  88801. _this.rawPose = null;
  88802. _this._specsVersion = "1.1";
  88803. _this._attached = false;
  88804. _this._descendants = [];
  88805. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  88806. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  88807. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  88808. _this._standingMatrix = null;
  88809. /**
  88810. * Represents device position in babylon space.
  88811. */
  88812. _this.devicePosition = BABYLON.Vector3.Zero();
  88813. /**
  88814. * Represents device rotation in babylon space.
  88815. */
  88816. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  88817. /**
  88818. * The scale of the device to be used when translating from device space to babylon space.
  88819. */
  88820. _this.deviceScaleFactor = 1;
  88821. _this._deviceToWorld = BABYLON.Matrix.Identity();
  88822. _this._worldToDevice = BABYLON.Matrix.Identity();
  88823. /**
  88824. * References to the webVR controllers for the vrDevice.
  88825. */
  88826. _this.controllers = [];
  88827. /**
  88828. * Emits an event when a controller is attached.
  88829. */
  88830. _this.onControllersAttachedObservable = new BABYLON.Observable();
  88831. /**
  88832. * Emits an event when a controller's mesh has been loaded;
  88833. */
  88834. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88835. /**
  88836. * If the rig cameras be used as parent instead of this camera.
  88837. */
  88838. _this.rigParenting = true;
  88839. _this._defaultHeight = undefined;
  88840. _this._workingVector = BABYLON.Vector3.Zero();
  88841. _this._oneVector = BABYLON.Vector3.One();
  88842. _this._workingMatrix = BABYLON.Matrix.Identity();
  88843. _this._cache.position = BABYLON.Vector3.Zero();
  88844. if (webVROptions.defaultHeight) {
  88845. _this._defaultHeight = webVROptions.defaultHeight;
  88846. _this.position.y = _this._defaultHeight;
  88847. }
  88848. _this.minZ = 0.1;
  88849. //legacy support - the compensation boolean was removed.
  88850. if (arguments.length === 5) {
  88851. _this.webVROptions = arguments[4];
  88852. }
  88853. // default webVR options
  88854. if (_this.webVROptions.trackPosition == undefined) {
  88855. _this.webVROptions.trackPosition = true;
  88856. }
  88857. if (_this.webVROptions.controllerMeshes == undefined) {
  88858. _this.webVROptions.controllerMeshes = true;
  88859. }
  88860. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  88861. _this.webVROptions.defaultLightingOnControllers = true;
  88862. }
  88863. _this.rotationQuaternion = new BABYLON.Quaternion();
  88864. if (_this.webVROptions && _this.webVROptions.positionScale) {
  88865. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  88866. }
  88867. //enable VR
  88868. var engine = _this.getEngine();
  88869. _this._onVREnabled = function (success) { if (success) {
  88870. _this.initControllers();
  88871. } };
  88872. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  88873. engine.initWebVR().add(function (event) {
  88874. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  88875. return;
  88876. }
  88877. _this._vrDevice = event.vrDisplay;
  88878. //reset the rig parameters.
  88879. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  88880. if (_this._attached) {
  88881. _this.getEngine().enableVR();
  88882. }
  88883. });
  88884. if (typeof (VRFrameData) !== "undefined")
  88885. _this._frameData = new VRFrameData();
  88886. /**
  88887. * The idea behind the following lines:
  88888. * objects that have the camera as parent should actually have the rig cameras as a parent.
  88889. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  88890. * the second will not show it correctly.
  88891. *
  88892. * To solve this - each object that has the camera as parent will be added to a protected array.
  88893. * When the rig camera renders, it will take this array and set all of those to be its children.
  88894. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  88895. * Amazing!
  88896. */
  88897. scene.onBeforeCameraRenderObservable.add(function (camera) {
  88898. if (camera.parent === _this && _this.rigParenting) {
  88899. _this._descendants = _this.getDescendants(true, function (n) {
  88900. // don't take the cameras or the controllers!
  88901. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  88902. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  88903. return !isController && !isRigCamera;
  88904. });
  88905. _this._descendants.forEach(function (node) {
  88906. node.parent = camera;
  88907. });
  88908. }
  88909. });
  88910. scene.onAfterCameraRenderObservable.add(function (camera) {
  88911. if (camera.parent === _this && _this.rigParenting) {
  88912. _this._descendants.forEach(function (node) {
  88913. node.parent = _this;
  88914. });
  88915. }
  88916. });
  88917. return _this;
  88918. }
  88919. /**
  88920. * Gets the device distance from the ground in meters.
  88921. * @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.
  88922. */
  88923. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  88924. if (this._standingMatrix) {
  88925. // Add standing matrix offset to get real offset from ground in room
  88926. this._standingMatrix.getTranslationToRef(this._workingVector);
  88927. return this._deviceRoomPosition.y + this._workingVector.y;
  88928. }
  88929. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  88930. return this._defaultHeight || 0;
  88931. };
  88932. /**
  88933. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88934. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  88935. */
  88936. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  88937. var _this = this;
  88938. if (callback === void 0) { callback = function (bool) { }; }
  88939. // Use standing matrix if available
  88940. this.getEngine().initWebVRAsync().then(function (result) {
  88941. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  88942. callback(false);
  88943. }
  88944. else {
  88945. _this._standingMatrix = new BABYLON.Matrix();
  88946. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  88947. if (!_this.getScene().useRightHandedSystem) {
  88948. [2, 6, 8, 9, 14].forEach(function (num) {
  88949. if (_this._standingMatrix) {
  88950. _this._standingMatrix.m[num] *= -1;
  88951. }
  88952. });
  88953. }
  88954. callback(true);
  88955. }
  88956. });
  88957. };
  88958. /**
  88959. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88960. * @returns A promise with a boolean set to if the standing matrix is supported.
  88961. */
  88962. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  88963. var _this = this;
  88964. return new Promise(function (res, rej) {
  88965. _this.useStandingMatrix(function (supported) {
  88966. res(supported);
  88967. });
  88968. });
  88969. };
  88970. /**
  88971. * Disposes the camera
  88972. */
  88973. WebVRFreeCamera.prototype.dispose = function () {
  88974. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  88975. _super.prototype.dispose.call(this);
  88976. };
  88977. /**
  88978. * Gets a vrController by name.
  88979. * @param name The name of the controller to retreive
  88980. * @returns the controller matching the name specified or null if not found
  88981. */
  88982. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  88983. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  88984. var gp = _a[_i];
  88985. if (gp.hand === name) {
  88986. return gp;
  88987. }
  88988. }
  88989. return null;
  88990. };
  88991. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  88992. /**
  88993. * The controller corrisponding to the users left hand.
  88994. */
  88995. get: function () {
  88996. if (!this._leftController) {
  88997. this._leftController = this.getControllerByName("left");
  88998. }
  88999. return this._leftController;
  89000. },
  89001. enumerable: true,
  89002. configurable: true
  89003. });
  89004. ;
  89005. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  89006. /**
  89007. * The controller corrisponding to the users right hand.
  89008. */
  89009. get: function () {
  89010. if (!this._rightController) {
  89011. this._rightController = this.getControllerByName("right");
  89012. }
  89013. return this._rightController;
  89014. },
  89015. enumerable: true,
  89016. configurable: true
  89017. });
  89018. ;
  89019. /**
  89020. * Casts a ray forward from the vrCamera's gaze.
  89021. * @param length Length of the ray (default: 100)
  89022. * @returns the ray corrisponding to the gaze
  89023. */
  89024. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  89025. if (length === void 0) { length = 100; }
  89026. if (this.leftCamera) {
  89027. // Use left eye to avoid computation to compute center on every call
  89028. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  89029. }
  89030. else {
  89031. return _super.prototype.getForwardRay.call(this, length);
  89032. }
  89033. };
  89034. /**
  89035. * Updates the camera based on device's frame data
  89036. */
  89037. WebVRFreeCamera.prototype._checkInputs = function () {
  89038. if (this._vrDevice && this._vrDevice.isPresenting) {
  89039. this._vrDevice.getFrameData(this._frameData);
  89040. this.updateFromDevice(this._frameData.pose);
  89041. }
  89042. _super.prototype._checkInputs.call(this);
  89043. };
  89044. /**
  89045. * Updates the poseControlled values based on the input device pose.
  89046. * @param poseData Pose coming from the device
  89047. */
  89048. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  89049. if (poseData && poseData.orientation) {
  89050. this.rawPose = poseData;
  89051. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  89052. if (this.getScene().useRightHandedSystem) {
  89053. this._deviceRoomRotationQuaternion.z *= -1;
  89054. this._deviceRoomRotationQuaternion.w *= -1;
  89055. }
  89056. if (this.webVROptions.trackPosition && this.rawPose.position) {
  89057. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  89058. if (this.getScene().useRightHandedSystem) {
  89059. this._deviceRoomPosition.z *= -1;
  89060. }
  89061. }
  89062. }
  89063. };
  89064. /**
  89065. * WebVR's attach control will start broadcasting frames to the device.
  89066. * Note that in certain browsers (chrome for example) this function must be called
  89067. * within a user-interaction callback. Example:
  89068. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  89069. *
  89070. * @param element html element to attach the vrDevice to
  89071. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  89072. */
  89073. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  89074. _super.prototype.attachControl.call(this, element, noPreventDefault);
  89075. this._attached = true;
  89076. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  89077. if (this._vrDevice) {
  89078. this.getEngine().enableVR();
  89079. }
  89080. };
  89081. /**
  89082. * Detaches the camera from the html element and disables VR
  89083. *
  89084. * @param element html element to detach from
  89085. */
  89086. WebVRFreeCamera.prototype.detachControl = function (element) {
  89087. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  89088. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  89089. _super.prototype.detachControl.call(this, element);
  89090. this._attached = false;
  89091. this.getEngine().disableVR();
  89092. };
  89093. /**
  89094. * @returns the name of this class
  89095. */
  89096. WebVRFreeCamera.prototype.getClassName = function () {
  89097. return "WebVRFreeCamera";
  89098. };
  89099. /**
  89100. * Calls resetPose on the vrDisplay
  89101. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  89102. */
  89103. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  89104. //uses the vrDisplay's "resetPose()".
  89105. //pitch and roll won't be affected.
  89106. this._vrDevice.resetPose();
  89107. };
  89108. /**
  89109. * Updates the rig cameras (left and right eye)
  89110. */
  89111. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89112. var camLeft = this._rigCameras[0];
  89113. var camRight = this._rigCameras[1];
  89114. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89115. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89116. camLeft.position.copyFrom(this._deviceRoomPosition);
  89117. camRight.position.copyFrom(this._deviceRoomPosition);
  89118. };
  89119. /**
  89120. * Updates the cached values of the camera
  89121. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89122. */
  89123. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89124. var _this = this;
  89125. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89126. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89127. if (!this.updateCacheCalled) {
  89128. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89129. this.updateCacheCalled = true;
  89130. this.update();
  89131. }
  89132. // Set working vector to the device position in room space rotated by the new rotation
  89133. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89134. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89135. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89136. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89137. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89138. // Add translation from anchor position
  89139. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89140. this._workingVector.addInPlace(this.position);
  89141. this._workingVector.subtractInPlace(this._cache.position);
  89142. this._deviceToWorld.setTranslation(this._workingVector);
  89143. // Set an inverted matrix to be used when updating the camera
  89144. this._deviceToWorld.invertToRef(this._worldToDevice);
  89145. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89146. this.controllers.forEach(function (controller) {
  89147. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89148. controller.update();
  89149. });
  89150. }
  89151. if (!ignoreParentClass) {
  89152. _super.prototype._updateCache.call(this);
  89153. }
  89154. this.updateCacheCalled = false;
  89155. };
  89156. /**
  89157. * Updates the current device position and rotation in the babylon world
  89158. */
  89159. WebVRFreeCamera.prototype.update = function () {
  89160. // Get current device position in babylon world
  89161. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89162. // Get current device rotation in babylon world
  89163. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89164. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89165. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89166. _super.prototype.update.call(this);
  89167. };
  89168. /**
  89169. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89170. * @returns an identity matrix
  89171. */
  89172. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89173. return BABYLON.Matrix.Identity();
  89174. };
  89175. /**
  89176. * This function is called by the two RIG cameras.
  89177. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89178. */
  89179. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89180. var _this = this;
  89181. // Update the parent camera prior to using a child camera to avoid desynchronization
  89182. var parentCamera = this._cameraRigParams["parentCamera"];
  89183. parentCamera._updateCache();
  89184. //WebVR 1.1
  89185. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89186. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89187. if (!this.getScene().useRightHandedSystem) {
  89188. [2, 6, 8, 9, 14].forEach(function (num) {
  89189. _this._webvrViewMatrix.m[num] *= -1;
  89190. });
  89191. }
  89192. // update the camera rotation matrix
  89193. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89194. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89195. // Computing target and final matrix
  89196. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89197. // should the view matrix be updated with scale and position offset?
  89198. if (parentCamera.deviceScaleFactor !== 1) {
  89199. this._webvrViewMatrix.invert();
  89200. // scale the position, if set
  89201. if (parentCamera.deviceScaleFactor) {
  89202. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89203. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89204. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89205. }
  89206. this._webvrViewMatrix.invert();
  89207. }
  89208. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89209. // Compute global position
  89210. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89211. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89212. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89213. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89214. this._markSyncedWithParent();
  89215. return this._webvrViewMatrix;
  89216. };
  89217. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89218. var _this = this;
  89219. var parentCamera = this.parent;
  89220. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89221. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89222. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89223. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89224. //babylon compatible matrix
  89225. if (!this.getScene().useRightHandedSystem) {
  89226. [8, 9, 10, 11].forEach(function (num) {
  89227. _this._projectionMatrix.m[num] *= -1;
  89228. });
  89229. }
  89230. return this._projectionMatrix;
  89231. };
  89232. /**
  89233. * Initializes the controllers and their meshes
  89234. */
  89235. WebVRFreeCamera.prototype.initControllers = function () {
  89236. var _this = this;
  89237. this.controllers = [];
  89238. var manager = this.getScene().gamepadManager;
  89239. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89240. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89241. var webVrController = gamepad;
  89242. if (webVrController.defaultModel) {
  89243. webVrController.defaultModel.setEnabled(false);
  89244. }
  89245. if (webVrController.hand === "right") {
  89246. _this._rightController = null;
  89247. }
  89248. if (webVrController.hand === "left") {
  89249. _this._leftController = null;
  89250. }
  89251. var controllerIndex = _this.controllers.indexOf(webVrController);
  89252. if (controllerIndex !== -1) {
  89253. _this.controllers.splice(controllerIndex, 1);
  89254. }
  89255. }
  89256. });
  89257. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89258. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89259. var webVrController_1 = gamepad;
  89260. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89261. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89262. if (_this.webVROptions.controllerMeshes) {
  89263. if (webVrController_1.defaultModel) {
  89264. webVrController_1.defaultModel.setEnabled(true);
  89265. }
  89266. else {
  89267. // Load the meshes
  89268. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89269. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89270. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89271. if (_this.webVROptions.defaultLightingOnControllers) {
  89272. if (!_this._lightOnControllers) {
  89273. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89274. }
  89275. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89276. var children = mesh.getChildren();
  89277. if (children.length !== 0) {
  89278. children.forEach(function (mesh) {
  89279. light.includedOnlyMeshes.push(mesh);
  89280. activateLightOnSubMeshes_1(mesh, light);
  89281. });
  89282. }
  89283. };
  89284. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89285. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89286. }
  89287. });
  89288. }
  89289. }
  89290. webVrController_1.attachToPoseControlledCamera(_this);
  89291. // since this is async - sanity check. Is the controller already stored?
  89292. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89293. //add to the controllers array
  89294. _this.controllers.push(webVrController_1);
  89295. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89296. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89297. // So we're overriding setting left & right manually to be sure
  89298. var firstViveWandDetected = false;
  89299. for (var i = 0; i < _this.controllers.length; i++) {
  89300. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89301. if (!firstViveWandDetected) {
  89302. firstViveWandDetected = true;
  89303. _this.controllers[i].hand = "left";
  89304. }
  89305. else {
  89306. _this.controllers[i].hand = "right";
  89307. }
  89308. }
  89309. }
  89310. //did we find enough controllers? Great! let the developer know.
  89311. if (_this.controllers.length >= 2) {
  89312. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89313. }
  89314. }
  89315. }
  89316. });
  89317. };
  89318. return WebVRFreeCamera;
  89319. }(BABYLON.FreeCamera));
  89320. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89321. })(BABYLON || (BABYLON = {}));
  89322. //# sourceMappingURL=babylon.webVRCamera.js.map
  89323. var BABYLON;
  89324. (function (BABYLON) {
  89325. // We're mainly based on the logic defined into the FreeCamera code
  89326. /**
  89327. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89328. * being tilted forward or back and left or right.
  89329. */
  89330. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89331. __extends(DeviceOrientationCamera, _super);
  89332. /**
  89333. * Creates a new device orientation camera
  89334. * @param name The name of the camera
  89335. * @param position The start position camera
  89336. * @param scene The scene the camera belongs to
  89337. */
  89338. function DeviceOrientationCamera(name, position, scene) {
  89339. var _this = _super.call(this, name, position, scene) || this;
  89340. _this._quaternionCache = new BABYLON.Quaternion();
  89341. _this.inputs.addDeviceOrientation();
  89342. return _this;
  89343. }
  89344. /**
  89345. * Gets the current instance class name ("DeviceOrientationCamera").
  89346. * This helps avoiding instanceof at run time.
  89347. * @returns the class name
  89348. */
  89349. DeviceOrientationCamera.prototype.getClassName = function () {
  89350. return "DeviceOrientationCamera";
  89351. };
  89352. /**
  89353. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89354. */
  89355. DeviceOrientationCamera.prototype._checkInputs = function () {
  89356. _super.prototype._checkInputs.call(this);
  89357. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89358. if (this._initialQuaternion) {
  89359. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89360. }
  89361. };
  89362. /**
  89363. * Reset the camera to its default orientation on the specified axis only.
  89364. * @param axis The axis to reset
  89365. */
  89366. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89367. var _this = this;
  89368. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89369. //can only work if this camera has a rotation quaternion already.
  89370. if (!this.rotationQuaternion)
  89371. return;
  89372. if (!this._initialQuaternion) {
  89373. this._initialQuaternion = new BABYLON.Quaternion();
  89374. }
  89375. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89376. ['x', 'y', 'z'].forEach(function (axisName) {
  89377. if (!axis[axisName]) {
  89378. _this._initialQuaternion[axisName] = 0;
  89379. }
  89380. else {
  89381. _this._initialQuaternion[axisName] *= -1;
  89382. }
  89383. });
  89384. this._initialQuaternion.normalize();
  89385. //force rotation update
  89386. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89387. };
  89388. return DeviceOrientationCamera;
  89389. }(BABYLON.FreeCamera));
  89390. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89391. })(BABYLON || (BABYLON = {}));
  89392. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89393. var BABYLON;
  89394. (function (BABYLON) {
  89395. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89396. __extends(VRDeviceOrientationFreeCamera, _super);
  89397. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89398. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89399. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89400. var _this = _super.call(this, name, position, scene) || this;
  89401. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89402. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89403. return _this;
  89404. }
  89405. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89406. return "VRDeviceOrientationFreeCamera";
  89407. };
  89408. return VRDeviceOrientationFreeCamera;
  89409. }(BABYLON.DeviceOrientationCamera));
  89410. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89411. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89412. __extends(VRDeviceOrientationGamepadCamera, _super);
  89413. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89414. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89415. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89416. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89417. _this.inputs.addGamepad();
  89418. return _this;
  89419. }
  89420. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89421. return "VRDeviceOrientationGamepadCamera";
  89422. };
  89423. return VRDeviceOrientationGamepadCamera;
  89424. }(VRDeviceOrientationFreeCamera));
  89425. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89426. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89427. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89428. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89429. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89430. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89431. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89432. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89433. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89434. _this.inputs.addVRDeviceOrientation();
  89435. return _this;
  89436. }
  89437. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89438. return "VRDeviceOrientationArcRotateCamera";
  89439. };
  89440. return VRDeviceOrientationArcRotateCamera;
  89441. }(BABYLON.ArcRotateCamera));
  89442. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89443. })(BABYLON || (BABYLON = {}));
  89444. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89445. var BABYLON;
  89446. (function (BABYLON) {
  89447. /**
  89448. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89449. */
  89450. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89451. __extends(AnaglyphFreeCamera, _super);
  89452. /**
  89453. * Creates a new AnaglyphFreeCamera
  89454. * @param name defines camera name
  89455. * @param position defines initial position
  89456. * @param interaxialDistance defines distance between each color axis
  89457. * @param scene defines the hosting scene
  89458. */
  89459. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89460. var _this = _super.call(this, name, position, scene) || this;
  89461. _this.interaxialDistance = interaxialDistance;
  89462. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89463. return _this;
  89464. }
  89465. /**
  89466. * Gets camera class name
  89467. * @returns AnaglyphFreeCamera
  89468. */
  89469. AnaglyphFreeCamera.prototype.getClassName = function () {
  89470. return "AnaglyphFreeCamera";
  89471. };
  89472. return AnaglyphFreeCamera;
  89473. }(BABYLON.FreeCamera));
  89474. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89475. /**
  89476. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89477. */
  89478. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89479. __extends(AnaglyphArcRotateCamera, _super);
  89480. /**
  89481. * Creates a new AnaglyphArcRotateCamera
  89482. * @param name defines camera name
  89483. * @param alpha defines alpha angle (in radians)
  89484. * @param beta defines beta angle (in radians)
  89485. * @param radius defines radius
  89486. * @param target defines camera target
  89487. * @param interaxialDistance defines distance between each color axis
  89488. * @param scene defines the hosting scene
  89489. */
  89490. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89491. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89492. _this.interaxialDistance = interaxialDistance;
  89493. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89494. return _this;
  89495. }
  89496. /**
  89497. * Gets camera class name
  89498. * @returns AnaglyphArcRotateCamera
  89499. */
  89500. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89501. return "AnaglyphArcRotateCamera";
  89502. };
  89503. return AnaglyphArcRotateCamera;
  89504. }(BABYLON.ArcRotateCamera));
  89505. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89506. /**
  89507. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89508. */
  89509. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89510. __extends(AnaglyphGamepadCamera, _super);
  89511. /**
  89512. * Creates a new AnaglyphGamepadCamera
  89513. * @param name defines camera name
  89514. * @param position defines initial position
  89515. * @param interaxialDistance defines distance between each color axis
  89516. * @param scene defines the hosting scene
  89517. */
  89518. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89519. var _this = _super.call(this, name, position, scene) || this;
  89520. _this.interaxialDistance = interaxialDistance;
  89521. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89522. return _this;
  89523. }
  89524. /**
  89525. * Gets camera class name
  89526. * @returns AnaglyphGamepadCamera
  89527. */
  89528. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89529. return "AnaglyphGamepadCamera";
  89530. };
  89531. return AnaglyphGamepadCamera;
  89532. }(BABYLON.GamepadCamera));
  89533. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89534. /**
  89535. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89536. */
  89537. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89538. __extends(AnaglyphUniversalCamera, _super);
  89539. /**
  89540. * Creates a new AnaglyphUniversalCamera
  89541. * @param name defines camera name
  89542. * @param position defines initial position
  89543. * @param interaxialDistance defines distance between each color axis
  89544. * @param scene defines the hosting scene
  89545. */
  89546. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89547. var _this = _super.call(this, name, position, scene) || this;
  89548. _this.interaxialDistance = interaxialDistance;
  89549. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89550. return _this;
  89551. }
  89552. /**
  89553. * Gets camera class name
  89554. * @returns AnaglyphUniversalCamera
  89555. */
  89556. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89557. return "AnaglyphUniversalCamera";
  89558. };
  89559. return AnaglyphUniversalCamera;
  89560. }(BABYLON.UniversalCamera));
  89561. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89562. /**
  89563. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89564. */
  89565. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89566. __extends(StereoscopicFreeCamera, _super);
  89567. /**
  89568. * Creates a new StereoscopicFreeCamera
  89569. * @param name defines camera name
  89570. * @param position defines initial position
  89571. * @param interaxialDistance defines distance between each color axis
  89572. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89573. * @param scene defines the hosting scene
  89574. */
  89575. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89576. var _this = _super.call(this, name, position, scene) || this;
  89577. _this.interaxialDistance = interaxialDistance;
  89578. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89579. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89580. return _this;
  89581. }
  89582. /**
  89583. * Gets camera class name
  89584. * @returns StereoscopicFreeCamera
  89585. */
  89586. StereoscopicFreeCamera.prototype.getClassName = function () {
  89587. return "StereoscopicFreeCamera";
  89588. };
  89589. return StereoscopicFreeCamera;
  89590. }(BABYLON.FreeCamera));
  89591. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89592. /**
  89593. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89594. */
  89595. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89596. __extends(StereoscopicArcRotateCamera, _super);
  89597. /**
  89598. * Creates a new StereoscopicArcRotateCamera
  89599. * @param name defines camera name
  89600. * @param alpha defines alpha angle (in radians)
  89601. * @param beta defines beta angle (in radians)
  89602. * @param radius defines radius
  89603. * @param target defines camera target
  89604. * @param interaxialDistance defines distance between each color axis
  89605. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89606. * @param scene defines the hosting scene
  89607. */
  89608. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  89609. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89610. _this.interaxialDistance = interaxialDistance;
  89611. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89612. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89613. return _this;
  89614. }
  89615. /**
  89616. * Gets camera class name
  89617. * @returns StereoscopicArcRotateCamera
  89618. */
  89619. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  89620. return "StereoscopicArcRotateCamera";
  89621. };
  89622. return StereoscopicArcRotateCamera;
  89623. }(BABYLON.ArcRotateCamera));
  89624. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  89625. /**
  89626. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  89627. */
  89628. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  89629. __extends(StereoscopicGamepadCamera, _super);
  89630. /**
  89631. * Creates a new StereoscopicGamepadCamera
  89632. * @param name defines camera name
  89633. * @param position defines initial position
  89634. * @param interaxialDistance defines distance between each color axis
  89635. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89636. * @param scene defines the hosting scene
  89637. */
  89638. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89639. var _this = _super.call(this, name, position, scene) || this;
  89640. _this.interaxialDistance = interaxialDistance;
  89641. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89642. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89643. return _this;
  89644. }
  89645. /**
  89646. * Gets camera class name
  89647. * @returns StereoscopicGamepadCamera
  89648. */
  89649. StereoscopicGamepadCamera.prototype.getClassName = function () {
  89650. return "StereoscopicGamepadCamera";
  89651. };
  89652. return StereoscopicGamepadCamera;
  89653. }(BABYLON.GamepadCamera));
  89654. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  89655. /**
  89656. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  89657. */
  89658. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  89659. __extends(StereoscopicUniversalCamera, _super);
  89660. /**
  89661. * Creates a new StereoscopicUniversalCamera
  89662. * @param name defines camera name
  89663. * @param position defines initial position
  89664. * @param interaxialDistance defines distance between each color axis
  89665. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89666. * @param scene defines the hosting scene
  89667. */
  89668. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89669. var _this = _super.call(this, name, position, scene) || this;
  89670. _this.interaxialDistance = interaxialDistance;
  89671. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89672. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89673. return _this;
  89674. }
  89675. /**
  89676. * Gets camera class name
  89677. * @returns StereoscopicUniversalCamera
  89678. */
  89679. StereoscopicUniversalCamera.prototype.getClassName = function () {
  89680. return "StereoscopicUniversalCamera";
  89681. };
  89682. return StereoscopicUniversalCamera;
  89683. }(BABYLON.UniversalCamera));
  89684. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  89685. })(BABYLON || (BABYLON = {}));
  89686. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  89687. var BABYLON;
  89688. (function (BABYLON) {
  89689. var VRExperienceHelperGazer = /** @class */ (function () {
  89690. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  89691. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  89692. this.scene = scene;
  89693. this._pointerDownOnMeshAsked = false;
  89694. this._isActionableMesh = false;
  89695. this._teleportationRequestInitiated = false;
  89696. this._teleportationBackRequestInitiated = false;
  89697. this._rotationRightAsked = false;
  89698. this._rotationLeftAsked = false;
  89699. this._dpadPressed = true;
  89700. this._activePointer = false;
  89701. this._id = VRExperienceHelperGazer._idCounter++;
  89702. // Gaze tracker
  89703. if (!gazeTrackerToClone) {
  89704. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  89705. this._gazeTracker.bakeCurrentTransformIntoVertices();
  89706. this._gazeTracker.isPickable = false;
  89707. this._gazeTracker.isVisible = false;
  89708. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  89709. targetMat.specularColor = BABYLON.Color3.Black();
  89710. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89711. targetMat.backFaceCulling = false;
  89712. this._gazeTracker.material = targetMat;
  89713. }
  89714. else {
  89715. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  89716. }
  89717. }
  89718. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  89719. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  89720. };
  89721. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  89722. this._pointerDownOnMeshAsked = true;
  89723. if (this._currentHit) {
  89724. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  89725. }
  89726. };
  89727. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  89728. if (this._currentHit) {
  89729. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  89730. }
  89731. this._pointerDownOnMeshAsked = false;
  89732. };
  89733. VRExperienceHelperGazer.prototype._activatePointer = function () {
  89734. this._activePointer = true;
  89735. };
  89736. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  89737. this._activePointer = false;
  89738. };
  89739. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  89740. if (distance === void 0) { distance = 100; }
  89741. };
  89742. VRExperienceHelperGazer.prototype.dispose = function () {
  89743. this._interactionsEnabled = false;
  89744. this._teleportationEnabled = false;
  89745. if (this._gazeTracker) {
  89746. this._gazeTracker.dispose();
  89747. }
  89748. };
  89749. VRExperienceHelperGazer._idCounter = 0;
  89750. return VRExperienceHelperGazer;
  89751. }());
  89752. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  89753. __extends(VRExperienceHelperControllerGazer, _super);
  89754. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  89755. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  89756. _this.webVRController = webVRController;
  89757. // Laser pointer
  89758. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  89759. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  89760. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89761. laserPointerMaterial.alpha = 0.6;
  89762. _this._laserPointer.material = laserPointerMaterial;
  89763. _this._laserPointer.rotation.x = Math.PI / 2;
  89764. _this._laserPointer.position.z = -0.5;
  89765. _this._laserPointer.isVisible = false;
  89766. if (!webVRController.mesh) {
  89767. // Create an empty mesh that is used prior to loading the high quality model
  89768. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  89769. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  89770. preloadPointerPose.rotation.x = -0.7;
  89771. preloadMesh.addChild(preloadPointerPose);
  89772. webVRController.attachToMesh(preloadMesh);
  89773. }
  89774. _this._setLaserPointerParent(webVRController.mesh);
  89775. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  89776. _this._setLaserPointerParent(mesh);
  89777. });
  89778. return _this;
  89779. }
  89780. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  89781. return this.webVRController.getForwardRay(length);
  89782. };
  89783. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  89784. _super.prototype._activatePointer.call(this);
  89785. this._laserPointer.isVisible = true;
  89786. };
  89787. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  89788. _super.prototype._deactivatePointer.call(this);
  89789. this._laserPointer.isVisible = false;
  89790. };
  89791. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  89792. this._laserPointer.material.emissiveColor = color;
  89793. };
  89794. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  89795. var makeNotPick = function (root) {
  89796. root.name += " laserPointer";
  89797. root.getChildMeshes().forEach(function (c) {
  89798. makeNotPick(c);
  89799. });
  89800. };
  89801. makeNotPick(mesh);
  89802. var childMeshes = mesh.getChildMeshes();
  89803. this.webVRController._pointingPoseNode = null;
  89804. for (var i = 0; i < childMeshes.length; i++) {
  89805. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  89806. mesh = childMeshes[i];
  89807. this.webVRController._pointingPoseNode = mesh;
  89808. break;
  89809. }
  89810. }
  89811. this._laserPointer.parent = mesh;
  89812. };
  89813. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  89814. if (distance === void 0) { distance = 100; }
  89815. this._laserPointer.scaling.y = distance;
  89816. this._laserPointer.position.z = -distance / 2;
  89817. };
  89818. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  89819. _super.prototype.dispose.call(this);
  89820. this._laserPointer.dispose();
  89821. if (this._meshAttachedObserver) {
  89822. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  89823. }
  89824. };
  89825. return VRExperienceHelperControllerGazer;
  89826. }(VRExperienceHelperGazer));
  89827. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  89828. __extends(VRExperienceHelperCameraGazer, _super);
  89829. function VRExperienceHelperCameraGazer(getCamera, scene) {
  89830. var _this = _super.call(this, scene) || this;
  89831. _this.getCamera = getCamera;
  89832. return _this;
  89833. }
  89834. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  89835. var camera = this.getCamera();
  89836. if (camera) {
  89837. return camera.getForwardRay(length);
  89838. }
  89839. else {
  89840. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  89841. }
  89842. };
  89843. return VRExperienceHelperCameraGazer;
  89844. }(VRExperienceHelperGazer));
  89845. /**
  89846. * Helps to quickly add VR support to an existing scene.
  89847. * See http://doc.babylonjs.com/how_to/webvr_helper
  89848. */
  89849. var VRExperienceHelper = /** @class */ (function () {
  89850. /**
  89851. * Instantiates a VRExperienceHelper.
  89852. * Helps to quickly add VR support to an existing scene.
  89853. * @param scene The scene the VRExperienceHelper belongs to.
  89854. * @param webVROptions Options to modify the vr experience helper's behavior.
  89855. */
  89856. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  89857. if (webVROptions === void 0) { webVROptions = {}; }
  89858. var _this = this;
  89859. this.webVROptions = webVROptions;
  89860. // Can the system support WebVR, even if a headset isn't plugged in?
  89861. this._webVRsupported = false;
  89862. // If WebVR is supported, is a headset plugged in and are we ready to present?
  89863. this._webVRready = false;
  89864. // Are we waiting for the requestPresent callback to complete?
  89865. this._webVRrequesting = false;
  89866. // Are we presenting to the headset right now?
  89867. this._webVRpresenting = false;
  89868. // Are we presenting in the fullscreen fallback?
  89869. this._fullscreenVRpresenting = false;
  89870. /**
  89871. * Observable raised when entering VR.
  89872. */
  89873. this.onEnteringVRObservable = new BABYLON.Observable();
  89874. /**
  89875. * Observable raised when exiting VR.
  89876. */
  89877. this.onExitingVRObservable = new BABYLON.Observable();
  89878. /**
  89879. * Observable raised when controller mesh is loaded.
  89880. */
  89881. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89882. this._useCustomVRButton = false;
  89883. this._teleportationRequested = false;
  89884. this._teleportActive = false;
  89885. this._floorMeshesCollection = [];
  89886. this._rotationAllowed = true;
  89887. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  89888. this._isDefaultTeleportationTarget = true;
  89889. this._teleportationFillColor = "#444444";
  89890. this._teleportationBorderColor = "#FFFFFF";
  89891. this._rotationAngle = 0;
  89892. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  89893. this._padSensibilityUp = 0.65;
  89894. this._padSensibilityDown = 0.35;
  89895. this.leftController = null;
  89896. this.rightController = null;
  89897. /**
  89898. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  89899. */
  89900. this.onNewMeshSelected = new BABYLON.Observable();
  89901. /**
  89902. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  89903. */
  89904. this.onNewMeshPicked = new BABYLON.Observable();
  89905. /**
  89906. * Observable raised before camera teleportation
  89907. */
  89908. this.onBeforeCameraTeleport = new BABYLON.Observable();
  89909. /**
  89910. * Observable raised after camera teleportation
  89911. */
  89912. this.onAfterCameraTeleport = new BABYLON.Observable();
  89913. /**
  89914. * Observable raised when current selected mesh gets unselected
  89915. */
  89916. this.onSelectedMeshUnselected = new BABYLON.Observable();
  89917. /**
  89918. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  89919. */
  89920. this.teleportationEnabled = true;
  89921. this._teleportationInitialized = false;
  89922. this._interactionsEnabled = false;
  89923. this._interactionsRequested = false;
  89924. this._displayGaze = true;
  89925. this._displayLaserPointer = true;
  89926. this._onResize = function () {
  89927. _this.moveButtonToBottomRight();
  89928. if (_this._fullscreenVRpresenting && _this._webVRready) {
  89929. _this.exitVR();
  89930. }
  89931. };
  89932. this._onFullscreenChange = function () {
  89933. if (document.fullscreen !== undefined) {
  89934. _this._fullscreenVRpresenting = document.fullscreen;
  89935. }
  89936. else if (document.mozFullScreen !== undefined) {
  89937. _this._fullscreenVRpresenting = document.mozFullScreen;
  89938. }
  89939. else if (document.webkitIsFullScreen !== undefined) {
  89940. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  89941. }
  89942. else if (document.msIsFullScreen !== undefined) {
  89943. _this._fullscreenVRpresenting = document.msIsFullScreen;
  89944. }
  89945. if (!_this._fullscreenVRpresenting && _this._canvas) {
  89946. _this.exitVR();
  89947. if (!_this._useCustomVRButton) {
  89948. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  89949. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  89950. }
  89951. }
  89952. };
  89953. this.beforeRender = function () {
  89954. if (_this.leftController && _this.leftController._activePointer) {
  89955. _this._castRayAndSelectObject(_this.leftController);
  89956. }
  89957. if (_this.rightController && _this.rightController._activePointer) {
  89958. _this._castRayAndSelectObject(_this.rightController);
  89959. }
  89960. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  89961. _this._castRayAndSelectObject(_this._cameraGazer);
  89962. }
  89963. else {
  89964. _this._cameraGazer._gazeTracker.isVisible = false;
  89965. }
  89966. };
  89967. this._onNewGamepadConnected = function (gamepad) {
  89968. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  89969. if (gamepad.leftStick) {
  89970. gamepad.onleftstickchanged(function (stickValues) {
  89971. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  89972. // Listening to classic/xbox gamepad only if no VR controller is active
  89973. if ((!_this.leftController && !_this.rightController) ||
  89974. ((_this.leftController && !_this.leftController._activePointer) &&
  89975. (_this.rightController && !_this.rightController._activePointer))) {
  89976. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  89977. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  89978. }
  89979. }
  89980. });
  89981. }
  89982. if (gamepad.rightStick) {
  89983. gamepad.onrightstickchanged(function (stickValues) {
  89984. if (_this._teleportationInitialized) {
  89985. _this._checkRotate(stickValues, _this._cameraGazer);
  89986. }
  89987. });
  89988. }
  89989. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  89990. gamepad.onbuttondown(function (buttonPressed) {
  89991. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89992. _this._cameraGazer._selectionPointerDown();
  89993. }
  89994. });
  89995. gamepad.onbuttonup(function (buttonPressed) {
  89996. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89997. _this._cameraGazer._selectionPointerUp();
  89998. }
  89999. });
  90000. }
  90001. }
  90002. else {
  90003. var webVRController = gamepad;
  90004. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  90005. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  90006. _this.rightController = controller;
  90007. }
  90008. else {
  90009. _this.leftController = controller;
  90010. }
  90011. _this._tryEnableInteractionOnController(controller);
  90012. }
  90013. };
  90014. // 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
  90015. this._tryEnableInteractionOnController = function (controller) {
  90016. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  90017. _this._enableInteractionOnController(controller);
  90018. }
  90019. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  90020. _this._enableTeleportationOnController(controller);
  90021. }
  90022. };
  90023. this._onNewGamepadDisconnected = function (gamepad) {
  90024. if (gamepad instanceof BABYLON.WebVRController) {
  90025. if (gamepad.hand === "left" && _this.leftController != null) {
  90026. _this.leftController.dispose();
  90027. _this.leftController = null;
  90028. }
  90029. if (gamepad.hand === "right" && _this.rightController != null) {
  90030. _this.rightController.dispose();
  90031. _this.rightController = null;
  90032. }
  90033. }
  90034. };
  90035. this._workingVector = BABYLON.Vector3.Zero();
  90036. this._workingQuaternion = BABYLON.Quaternion.Identity();
  90037. this._workingMatrix = BABYLON.Matrix.Identity();
  90038. this._scene = scene;
  90039. this._canvas = scene.getEngine().getRenderingCanvas();
  90040. // Parse options
  90041. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  90042. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  90043. }
  90044. if (webVROptions.createDeviceOrientationCamera === undefined) {
  90045. webVROptions.createDeviceOrientationCamera = true;
  90046. }
  90047. if (webVROptions.laserToggle === undefined) {
  90048. webVROptions.laserToggle = true;
  90049. }
  90050. if (webVROptions.defaultHeight === undefined) {
  90051. webVROptions.defaultHeight = 1.7;
  90052. }
  90053. if (webVROptions.useCustomVRButton) {
  90054. this._useCustomVRButton = true;
  90055. if (webVROptions.customVRButton) {
  90056. this._btnVR = webVROptions.customVRButton;
  90057. }
  90058. }
  90059. if (webVROptions.rayLength) {
  90060. this._rayLength = webVROptions.rayLength;
  90061. }
  90062. this._defaultHeight = webVROptions.defaultHeight;
  90063. if (webVROptions.positionScale) {
  90064. this._rayLength *= webVROptions.positionScale;
  90065. this._defaultHeight *= webVROptions.positionScale;
  90066. }
  90067. // Set position
  90068. if (this._scene.activeCamera) {
  90069. this._position = this._scene.activeCamera.position.clone();
  90070. }
  90071. else {
  90072. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  90073. }
  90074. // Set non-vr camera
  90075. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  90076. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  90077. // Copy data from existing camera
  90078. if (this._scene.activeCamera) {
  90079. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90080. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  90081. // Set rotation from previous camera
  90082. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  90083. var targetCamera = this._scene.activeCamera;
  90084. if (targetCamera.rotationQuaternion) {
  90085. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  90086. }
  90087. else {
  90088. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  90089. }
  90090. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  90091. }
  90092. }
  90093. this._scene.activeCamera = this._deviceOrientationCamera;
  90094. if (this._canvas) {
  90095. this._scene.activeCamera.attachControl(this._canvas);
  90096. }
  90097. }
  90098. else {
  90099. this._existingCamera = this._scene.activeCamera;
  90100. }
  90101. // Create VR cameras
  90102. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90103. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  90104. }
  90105. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  90106. this._webVRCamera.useStandingMatrix();
  90107. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  90108. // Create default button
  90109. if (!this._useCustomVRButton) {
  90110. this._btnVR = document.createElement("BUTTON");
  90111. this._btnVR.className = "babylonVRicon";
  90112. this._btnVR.id = "babylonVRiconbtn";
  90113. this._btnVR.title = "Click to switch to VR";
  90114. 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) }";
  90115. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90116. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90117. // css += ".babylonVRicon.vrdisplaysupported { }";
  90118. // css += ".babylonVRicon.vrdisplayready { }";
  90119. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90120. var style = document.createElement('style');
  90121. style.appendChild(document.createTextNode(css));
  90122. document.getElementsByTagName('head')[0].appendChild(style);
  90123. this.moveButtonToBottomRight();
  90124. }
  90125. // VR button click event
  90126. if (this._btnVR) {
  90127. this._btnVR.addEventListener("click", function () {
  90128. if (!_this.isInVRMode) {
  90129. _this.enterVR();
  90130. }
  90131. else {
  90132. _this.exitVR();
  90133. }
  90134. });
  90135. }
  90136. // Window events
  90137. window.addEventListener("resize", this._onResize);
  90138. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90139. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90140. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90141. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90142. // Display vr button when headset is connected
  90143. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90144. this.displayVRButton();
  90145. }
  90146. else {
  90147. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90148. if (e.vrDisplay) {
  90149. _this.displayVRButton();
  90150. }
  90151. });
  90152. }
  90153. // Exiting VR mode using 'ESC' key on desktop
  90154. this._onKeyDown = function (event) {
  90155. if (event.keyCode === 27 && _this.isInVRMode) {
  90156. _this.exitVR();
  90157. }
  90158. };
  90159. document.addEventListener("keydown", this._onKeyDown);
  90160. // Exiting VR mode double tapping the touch screen
  90161. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90162. if (_this.isInVRMode) {
  90163. _this.exitVR();
  90164. if (_this._fullscreenVRpresenting) {
  90165. _this._scene.getEngine().switchFullscreen(true);
  90166. }
  90167. }
  90168. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90169. // Listen for WebVR display changes
  90170. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90171. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90172. this._onVRRequestPresentStart = function () {
  90173. _this._webVRrequesting = true;
  90174. _this.updateButtonVisibility();
  90175. };
  90176. this._onVRRequestPresentComplete = function (success) {
  90177. _this._webVRrequesting = false;
  90178. _this.updateButtonVisibility();
  90179. };
  90180. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90181. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90182. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90183. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90184. scene.onDisposeObservable.add(function () {
  90185. _this.dispose();
  90186. });
  90187. // Gamepad connection events
  90188. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90189. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90190. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90191. this.updateButtonVisibility();
  90192. //create easing functions
  90193. this._circleEase = new BABYLON.CircleEase();
  90194. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90195. if (this.webVROptions.floorMeshes) {
  90196. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90197. }
  90198. }
  90199. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90200. /** Return this.onEnteringVRObservable
  90201. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90202. */
  90203. get: function () {
  90204. return this.onEnteringVRObservable;
  90205. },
  90206. enumerable: true,
  90207. configurable: true
  90208. });
  90209. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90210. /** Return this.onExitingVRObservable
  90211. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90212. */
  90213. get: function () {
  90214. return this.onExitingVRObservable;
  90215. },
  90216. enumerable: true,
  90217. configurable: true
  90218. });
  90219. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90220. /** Return this.onControllerMeshLoadedObservable
  90221. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90222. */
  90223. get: function () {
  90224. return this.onControllerMeshLoadedObservable;
  90225. },
  90226. enumerable: true,
  90227. configurable: true
  90228. });
  90229. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90230. /**
  90231. * The mesh used to display where the user is going to teleport.
  90232. */
  90233. get: function () {
  90234. return this._teleportationTarget;
  90235. },
  90236. /**
  90237. * Sets the mesh to be used to display where the user is going to teleport.
  90238. */
  90239. set: function (value) {
  90240. if (value) {
  90241. value.name = "teleportationTarget";
  90242. this._isDefaultTeleportationTarget = false;
  90243. this._teleportationTarget = value;
  90244. }
  90245. },
  90246. enumerable: true,
  90247. configurable: true
  90248. });
  90249. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90250. /**
  90251. * The mesh used to display where the user is selecting,
  90252. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90253. * See http://doc.babylonjs.com/resources/baking_transformations
  90254. */
  90255. get: function () {
  90256. return this._cameraGazer._gazeTracker;
  90257. },
  90258. set: function (value) {
  90259. if (value) {
  90260. this._cameraGazer._gazeTracker = value;
  90261. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90262. this._cameraGazer._gazeTracker.isPickable = false;
  90263. this._cameraGazer._gazeTracker.isVisible = false;
  90264. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90265. if (this.leftController) {
  90266. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90267. }
  90268. if (this.rightController) {
  90269. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90270. }
  90271. }
  90272. },
  90273. enumerable: true,
  90274. configurable: true
  90275. });
  90276. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90277. /**
  90278. * If the ray of the gaze should be displayed.
  90279. */
  90280. get: function () {
  90281. return this._displayGaze;
  90282. },
  90283. /**
  90284. * Sets if the ray of the gaze should be displayed.
  90285. */
  90286. set: function (value) {
  90287. this._displayGaze = value;
  90288. if (!value) {
  90289. this._cameraGazer._gazeTracker.isVisible = false;
  90290. if (this.leftController) {
  90291. this.leftController._gazeTracker.isVisible = false;
  90292. }
  90293. if (this.rightController) {
  90294. this.rightController._gazeTracker.isVisible = false;
  90295. }
  90296. }
  90297. },
  90298. enumerable: true,
  90299. configurable: true
  90300. });
  90301. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90302. /**
  90303. * If the ray of the LaserPointer should be displayed.
  90304. */
  90305. get: function () {
  90306. return this._displayLaserPointer;
  90307. },
  90308. /**
  90309. * Sets if the ray of the LaserPointer should be displayed.
  90310. */
  90311. set: function (value) {
  90312. this._displayLaserPointer = value;
  90313. if (!value) {
  90314. if (this.rightController) {
  90315. this.rightController._deactivatePointer();
  90316. this.rightController._gazeTracker.isVisible = false;
  90317. }
  90318. if (this.leftController) {
  90319. this.leftController._deactivatePointer();
  90320. this.leftController._gazeTracker.isVisible = false;
  90321. }
  90322. }
  90323. else {
  90324. if (this.rightController) {
  90325. this.rightController._activatePointer();
  90326. }
  90327. if (this.leftController) {
  90328. this.leftController._activatePointer();
  90329. }
  90330. }
  90331. },
  90332. enumerable: true,
  90333. configurable: true
  90334. });
  90335. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90336. /**
  90337. * The deviceOrientationCamera used as the camera when not in VR.
  90338. */
  90339. get: function () {
  90340. return this._deviceOrientationCamera;
  90341. },
  90342. enumerable: true,
  90343. configurable: true
  90344. });
  90345. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90346. /**
  90347. * Based on the current WebVR support, returns the current VR camera used.
  90348. */
  90349. get: function () {
  90350. if (this._webVRready) {
  90351. return this._webVRCamera;
  90352. }
  90353. else {
  90354. return this._scene.activeCamera;
  90355. }
  90356. },
  90357. enumerable: true,
  90358. configurable: true
  90359. });
  90360. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90361. /**
  90362. * The webVRCamera which is used when in VR.
  90363. */
  90364. get: function () {
  90365. return this._webVRCamera;
  90366. },
  90367. enumerable: true,
  90368. configurable: true
  90369. });
  90370. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90371. /**
  90372. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90373. */
  90374. get: function () {
  90375. return this._vrDeviceOrientationCamera;
  90376. },
  90377. enumerable: true,
  90378. configurable: true
  90379. });
  90380. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90381. get: function () {
  90382. var result = this._cameraGazer._teleportationRequestInitiated
  90383. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90384. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90385. return result;
  90386. },
  90387. enumerable: true,
  90388. configurable: true
  90389. });
  90390. // Raised when one of the controller has loaded successfully its associated default mesh
  90391. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90392. if (this.leftController && this.leftController.webVRController == webVRController) {
  90393. if (webVRController.mesh) {
  90394. this.leftController._setLaserPointerParent(webVRController.mesh);
  90395. }
  90396. }
  90397. if (this.rightController && this.rightController.webVRController == webVRController) {
  90398. if (webVRController.mesh) {
  90399. this.rightController._setLaserPointerParent(webVRController.mesh);
  90400. }
  90401. }
  90402. try {
  90403. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90404. }
  90405. catch (err) {
  90406. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90407. }
  90408. };
  90409. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90410. /**
  90411. * Gets a value indicating if we are currently in VR mode.
  90412. */
  90413. get: function () {
  90414. return this._webVRpresenting || this._fullscreenVRpresenting;
  90415. },
  90416. enumerable: true,
  90417. configurable: true
  90418. });
  90419. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90420. var vrDisplay = this._scene.getEngine().getVRDevice();
  90421. if (vrDisplay) {
  90422. var wasPresenting = this._webVRpresenting;
  90423. // A VR display is connected
  90424. this._webVRpresenting = vrDisplay.isPresenting;
  90425. if (wasPresenting && !this._webVRpresenting)
  90426. this.exitVR();
  90427. }
  90428. else {
  90429. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90430. }
  90431. this.updateButtonVisibility();
  90432. };
  90433. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90434. this._webVRsupported = eventArgs.vrSupported;
  90435. this._webVRready = !!eventArgs.vrDisplay;
  90436. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90437. this.updateButtonVisibility();
  90438. };
  90439. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90440. if (this._canvas && !this._useCustomVRButton) {
  90441. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90442. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90443. }
  90444. };
  90445. VRExperienceHelper.prototype.displayVRButton = function () {
  90446. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90447. document.body.appendChild(this._btnVR);
  90448. this._btnVRDisplayed = true;
  90449. }
  90450. };
  90451. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90452. if (!this._btnVR || this._useCustomVRButton) {
  90453. return;
  90454. }
  90455. this._btnVR.className = "babylonVRicon";
  90456. if (this.isInVRMode) {
  90457. this._btnVR.className += " vrdisplaypresenting";
  90458. }
  90459. else {
  90460. if (this._webVRready)
  90461. this._btnVR.className += " vrdisplayready";
  90462. if (this._webVRsupported)
  90463. this._btnVR.className += " vrdisplaysupported";
  90464. if (this._webVRrequesting)
  90465. this._btnVR.className += " vrdisplayrequesting";
  90466. }
  90467. };
  90468. /**
  90469. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90470. * Otherwise, will use the fullscreen API.
  90471. */
  90472. VRExperienceHelper.prototype.enterVR = function () {
  90473. if (this.onEnteringVRObservable) {
  90474. try {
  90475. this.onEnteringVRObservable.notifyObservers(this);
  90476. }
  90477. catch (err) {
  90478. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90479. }
  90480. }
  90481. if (this._scene.activeCamera) {
  90482. this._position = this._scene.activeCamera.position.clone();
  90483. // make sure that we return to the last active camera
  90484. this._existingCamera = this._scene.activeCamera;
  90485. }
  90486. if (this._webVRrequesting)
  90487. return;
  90488. // If WebVR is supported and a headset is connected
  90489. if (this._webVRready) {
  90490. if (!this._webVRpresenting) {
  90491. this._webVRCamera.position = this._position;
  90492. this._scene.activeCamera = this._webVRCamera;
  90493. }
  90494. }
  90495. else if (this._vrDeviceOrientationCamera) {
  90496. this._vrDeviceOrientationCamera.position = this._position;
  90497. if (this._scene.activeCamera) {
  90498. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90499. }
  90500. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90501. this._scene.getEngine().switchFullscreen(true);
  90502. this.updateButtonVisibility();
  90503. }
  90504. if (this._scene.activeCamera && this._canvas) {
  90505. this._scene.activeCamera.attachControl(this._canvas);
  90506. }
  90507. if (this._interactionsEnabled) {
  90508. this._scene.registerBeforeRender(this.beforeRender);
  90509. }
  90510. };
  90511. /**
  90512. * Attempt to exit VR, or fullscreen.
  90513. */
  90514. VRExperienceHelper.prototype.exitVR = function () {
  90515. if (this.onExitingVRObservable) {
  90516. try {
  90517. this.onExitingVRObservable.notifyObservers(this);
  90518. }
  90519. catch (err) {
  90520. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90521. }
  90522. }
  90523. if (this._webVRpresenting) {
  90524. this._scene.getEngine().disableVR();
  90525. }
  90526. if (this._scene.activeCamera) {
  90527. this._position = this._scene.activeCamera.position.clone();
  90528. }
  90529. if (this._deviceOrientationCamera) {
  90530. this._deviceOrientationCamera.position = this._position;
  90531. this._scene.activeCamera = this._deviceOrientationCamera;
  90532. if (this._canvas) {
  90533. this._scene.activeCamera.attachControl(this._canvas);
  90534. }
  90535. }
  90536. else if (this._existingCamera) {
  90537. this._existingCamera.position = this._position;
  90538. this._scene.activeCamera = this._existingCamera;
  90539. }
  90540. this.updateButtonVisibility();
  90541. if (this._interactionsEnabled) {
  90542. this._scene.unregisterBeforeRender(this.beforeRender);
  90543. }
  90544. // resize to update width and height when exiting vr exits fullscreen
  90545. this._scene.getEngine().resize();
  90546. };
  90547. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90548. /**
  90549. * The position of the vr experience helper.
  90550. */
  90551. get: function () {
  90552. return this._position;
  90553. },
  90554. /**
  90555. * Sets the position of the vr experience helper.
  90556. */
  90557. set: function (value) {
  90558. this._position = value;
  90559. if (this._scene.activeCamera) {
  90560. this._scene.activeCamera.position = value;
  90561. }
  90562. },
  90563. enumerable: true,
  90564. configurable: true
  90565. });
  90566. /**
  90567. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90568. */
  90569. VRExperienceHelper.prototype.enableInteractions = function () {
  90570. var _this = this;
  90571. if (!this._interactionsEnabled) {
  90572. this._interactionsRequested = true;
  90573. if (this.leftController) {
  90574. this._enableInteractionOnController(this.leftController);
  90575. }
  90576. if (this.rightController) {
  90577. this._enableInteractionOnController(this.rightController);
  90578. }
  90579. this.raySelectionPredicate = function (mesh) {
  90580. return mesh.isVisible;
  90581. };
  90582. this.meshSelectionPredicate = function (mesh) {
  90583. return true;
  90584. };
  90585. this._raySelectionPredicate = function (mesh) {
  90586. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90587. && mesh.name.indexOf("teleportationTarget") === -1
  90588. && mesh.name.indexOf("torusTeleportation") === -1
  90589. && mesh.name.indexOf("laserPointer") === -1)) {
  90590. return _this.raySelectionPredicate(mesh);
  90591. }
  90592. return false;
  90593. };
  90594. this._interactionsEnabled = true;
  90595. }
  90596. };
  90597. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  90598. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  90599. if (this._floorMeshesCollection[i].id === mesh.id) {
  90600. return true;
  90601. }
  90602. }
  90603. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  90604. return true;
  90605. }
  90606. return false;
  90607. };
  90608. /**
  90609. * Adds a floor mesh to be used for teleportation.
  90610. * @param floorMesh the mesh to be used for teleportation.
  90611. */
  90612. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  90613. if (!this._floorMeshesCollection) {
  90614. return;
  90615. }
  90616. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  90617. return;
  90618. }
  90619. this._floorMeshesCollection.push(floorMesh);
  90620. };
  90621. /**
  90622. * Removes a floor mesh from being used for teleportation.
  90623. * @param floorMesh the mesh to be removed.
  90624. */
  90625. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  90626. if (!this._floorMeshesCollection) {
  90627. return;
  90628. }
  90629. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  90630. if (meshIndex !== -1) {
  90631. this._floorMeshesCollection.splice(meshIndex, 1);
  90632. }
  90633. };
  90634. /**
  90635. * Enables interactions and teleportation using the VR controllers and gaze.
  90636. * @param vrTeleportationOptions options to modify teleportation behavior.
  90637. */
  90638. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  90639. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  90640. if (!this._teleportationInitialized) {
  90641. this._teleportationRequested = true;
  90642. this.enableInteractions();
  90643. if (vrTeleportationOptions.floorMeshName) {
  90644. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  90645. }
  90646. if (vrTeleportationOptions.floorMeshes) {
  90647. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  90648. }
  90649. if (this.leftController != null) {
  90650. this._enableTeleportationOnController(this.leftController);
  90651. }
  90652. if (this.rightController != null) {
  90653. this._enableTeleportationOnController(this.rightController);
  90654. }
  90655. // Creates an image processing post process for the vignette not relying
  90656. // on the main scene configuration for image processing to reduce setup and spaces
  90657. // (gamma/linear) conflicts.
  90658. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  90659. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  90660. imageProcessingConfiguration.vignetteEnabled = true;
  90661. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  90662. this._webVRCamera.detachPostProcess(this._postProcessMove);
  90663. this._teleportationInitialized = true;
  90664. if (this._isDefaultTeleportationTarget) {
  90665. this._createTeleportationCircles();
  90666. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  90667. }
  90668. }
  90669. };
  90670. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  90671. var _this = this;
  90672. var controllerMesh = controller.webVRController.mesh;
  90673. if (controllerMesh) {
  90674. controller._interactionsEnabled = true;
  90675. controller._activatePointer();
  90676. if (this.webVROptions.laserToggle) {
  90677. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  90678. // Enabling / disabling laserPointer
  90679. if (_this._displayLaserPointer && stateObject.value === 1) {
  90680. if (controller._activePointer) {
  90681. controller._deactivatePointer();
  90682. }
  90683. else {
  90684. controller._activatePointer();
  90685. }
  90686. if (_this.displayGaze) {
  90687. controller._gazeTracker.isVisible = controller._activePointer;
  90688. }
  90689. }
  90690. });
  90691. }
  90692. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  90693. if (!controller._pointerDownOnMeshAsked) {
  90694. if (stateObject.value > _this._padSensibilityUp) {
  90695. controller._selectionPointerDown();
  90696. }
  90697. }
  90698. else if (stateObject.value < _this._padSensibilityDown) {
  90699. controller._selectionPointerUp();
  90700. }
  90701. });
  90702. }
  90703. };
  90704. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  90705. // Dont teleport if another gaze already requested teleportation
  90706. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  90707. return;
  90708. }
  90709. if (!gazer._teleportationRequestInitiated) {
  90710. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  90711. gazer._activatePointer();
  90712. gazer._teleportationRequestInitiated = true;
  90713. }
  90714. }
  90715. else {
  90716. // Listening to the proper controller values changes to confirm teleportation
  90717. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  90718. if (this._teleportActive) {
  90719. this._teleportCamera(this._haloCenter);
  90720. }
  90721. gazer._teleportationRequestInitiated = false;
  90722. }
  90723. }
  90724. };
  90725. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  90726. // Only rotate when user is not currently selecting a teleportation location
  90727. if (gazer._teleportationRequestInitiated) {
  90728. return;
  90729. }
  90730. if (!gazer._rotationLeftAsked) {
  90731. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  90732. gazer._rotationLeftAsked = true;
  90733. if (this._rotationAllowed) {
  90734. this._rotateCamera(false);
  90735. }
  90736. }
  90737. }
  90738. else {
  90739. if (stateObject.x > -this._padSensibilityDown) {
  90740. gazer._rotationLeftAsked = false;
  90741. }
  90742. }
  90743. if (!gazer._rotationRightAsked) {
  90744. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  90745. gazer._rotationRightAsked = true;
  90746. if (this._rotationAllowed) {
  90747. this._rotateCamera(true);
  90748. }
  90749. }
  90750. }
  90751. else {
  90752. if (stateObject.x < this._padSensibilityDown) {
  90753. gazer._rotationRightAsked = false;
  90754. }
  90755. }
  90756. };
  90757. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  90758. // Only teleport backwards when user is not currently selecting a teleportation location
  90759. if (gazer._teleportationRequestInitiated) {
  90760. return;
  90761. }
  90762. // Teleport backwards
  90763. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  90764. if (!gazer._teleportationBackRequestInitiated) {
  90765. if (!this.currentVRCamera) {
  90766. return;
  90767. }
  90768. // Get rotation and position of the current camera
  90769. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  90770. var position = this.currentVRCamera.position;
  90771. // If the camera has device position, use that instead
  90772. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  90773. rotation = this.currentVRCamera.deviceRotationQuaternion;
  90774. position = this.currentVRCamera.devicePosition;
  90775. }
  90776. // Get matrix with only the y rotation of the device rotation
  90777. rotation.toEulerAnglesToRef(this._workingVector);
  90778. this._workingVector.z = 0;
  90779. this._workingVector.x = 0;
  90780. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  90781. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  90782. // Rotate backwards ray by device rotation to cast at the ground behind the user
  90783. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  90784. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  90785. var ray = new BABYLON.Ray(position, this._workingVector);
  90786. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90787. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  90788. this._teleportCamera(hit.pickedPoint);
  90789. }
  90790. gazer._teleportationBackRequestInitiated = true;
  90791. }
  90792. }
  90793. else {
  90794. gazer._teleportationBackRequestInitiated = false;
  90795. }
  90796. };
  90797. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  90798. var _this = this;
  90799. var controllerMesh = controller.webVRController.mesh;
  90800. if (controllerMesh) {
  90801. if (!controller._interactionsEnabled) {
  90802. this._enableInteractionOnController(controller);
  90803. }
  90804. controller._interactionsEnabled = true;
  90805. controller._teleportationEnabled = true;
  90806. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90807. controller._dpadPressed = false;
  90808. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  90809. controller._dpadPressed = stateObject.pressed;
  90810. if (!controller._dpadPressed) {
  90811. controller._rotationLeftAsked = false;
  90812. controller._rotationRightAsked = false;
  90813. controller._teleportationBackRequestInitiated = false;
  90814. }
  90815. });
  90816. }
  90817. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  90818. if (_this.teleportationEnabled) {
  90819. _this._checkTeleportBackwards(stateObject, controller);
  90820. _this._checkTeleportWithRay(stateObject, controller);
  90821. }
  90822. _this._checkRotate(stateObject, controller);
  90823. });
  90824. }
  90825. };
  90826. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  90827. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  90828. this._teleportationTarget.isPickable = false;
  90829. var length = 512;
  90830. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  90831. dynamicTexture.hasAlpha = true;
  90832. var context = dynamicTexture.getContext();
  90833. var centerX = length / 2;
  90834. var centerY = length / 2;
  90835. var radius = 200;
  90836. context.beginPath();
  90837. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  90838. context.fillStyle = this._teleportationFillColor;
  90839. context.fill();
  90840. context.lineWidth = 10;
  90841. context.strokeStyle = this._teleportationBorderColor;
  90842. context.stroke();
  90843. context.closePath();
  90844. dynamicTexture.update();
  90845. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  90846. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  90847. this._teleportationTarget.material = teleportationCircleMaterial;
  90848. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  90849. torus.isPickable = false;
  90850. torus.parent = this._teleportationTarget;
  90851. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90852. var keys = [];
  90853. keys.push({
  90854. frame: 0,
  90855. value: 0
  90856. });
  90857. keys.push({
  90858. frame: 30,
  90859. value: 0.4
  90860. });
  90861. keys.push({
  90862. frame: 60,
  90863. value: 0
  90864. });
  90865. animationInnerCircle.setKeys(keys);
  90866. var easingFunction = new BABYLON.SineEase();
  90867. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90868. animationInnerCircle.setEasingFunction(easingFunction);
  90869. torus.animations = [];
  90870. torus.animations.push(animationInnerCircle);
  90871. this._scene.beginAnimation(torus, 0, 60, true);
  90872. this._hideTeleportationTarget();
  90873. };
  90874. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  90875. this._teleportActive = true;
  90876. if (this._teleportationInitialized) {
  90877. this._teleportationTarget.isVisible = true;
  90878. if (this._isDefaultTeleportationTarget) {
  90879. this._teleportationTarget.getChildren()[0].isVisible = true;
  90880. }
  90881. }
  90882. };
  90883. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  90884. this._teleportActive = false;
  90885. if (this._teleportationInitialized) {
  90886. this._teleportationTarget.isVisible = false;
  90887. if (this._isDefaultTeleportationTarget) {
  90888. this._teleportationTarget.getChildren()[0].isVisible = false;
  90889. }
  90890. }
  90891. };
  90892. VRExperienceHelper.prototype._rotateCamera = function (right) {
  90893. var _this = this;
  90894. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90895. return;
  90896. }
  90897. if (right) {
  90898. this._rotationAngle++;
  90899. }
  90900. else {
  90901. this._rotationAngle--;
  90902. }
  90903. this.currentVRCamera.animations = [];
  90904. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  90905. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90906. var animationRotationKeys = [];
  90907. animationRotationKeys.push({
  90908. frame: 0,
  90909. value: this.currentVRCamera.rotationQuaternion
  90910. });
  90911. animationRotationKeys.push({
  90912. frame: 6,
  90913. value: target
  90914. });
  90915. animationRotation.setKeys(animationRotationKeys);
  90916. animationRotation.setEasingFunction(this._circleEase);
  90917. this.currentVRCamera.animations.push(animationRotation);
  90918. this._postProcessMove.animations = [];
  90919. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90920. var vignetteWeightKeys = [];
  90921. vignetteWeightKeys.push({
  90922. frame: 0,
  90923. value: 0
  90924. });
  90925. vignetteWeightKeys.push({
  90926. frame: 3,
  90927. value: 4
  90928. });
  90929. vignetteWeightKeys.push({
  90930. frame: 6,
  90931. value: 0
  90932. });
  90933. animationPP.setKeys(vignetteWeightKeys);
  90934. animationPP.setEasingFunction(this._circleEase);
  90935. this._postProcessMove.animations.push(animationPP);
  90936. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90937. var vignetteStretchKeys = [];
  90938. vignetteStretchKeys.push({
  90939. frame: 0,
  90940. value: 0
  90941. });
  90942. vignetteStretchKeys.push({
  90943. frame: 3,
  90944. value: 10
  90945. });
  90946. vignetteStretchKeys.push({
  90947. frame: 6,
  90948. value: 0
  90949. });
  90950. animationPP2.setKeys(vignetteStretchKeys);
  90951. animationPP2.setEasingFunction(this._circleEase);
  90952. this._postProcessMove.animations.push(animationPP2);
  90953. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90954. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90955. this._postProcessMove.samples = 4;
  90956. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90957. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  90958. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90959. });
  90960. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  90961. };
  90962. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  90963. if (hit.pickedPoint) {
  90964. if (gazer._teleportationRequestInitiated) {
  90965. this._displayTeleportationTarget();
  90966. this._haloCenter.copyFrom(hit.pickedPoint);
  90967. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  90968. }
  90969. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  90970. if (pickNormal) {
  90971. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  90972. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  90973. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  90974. }
  90975. this._teleportationTarget.position.y += 0.1;
  90976. }
  90977. };
  90978. VRExperienceHelper.prototype._teleportCamera = function (location) {
  90979. var _this = this;
  90980. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90981. return;
  90982. }
  90983. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  90984. // offset of the headset from the anchor.
  90985. if (this.webVRCamera.leftCamera) {
  90986. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  90987. this._workingVector.subtractInPlace(this.webVRCamera.position);
  90988. location.subtractToRef(this._workingVector, this._workingVector);
  90989. }
  90990. else {
  90991. this._workingVector.copyFrom(location);
  90992. }
  90993. // Add height to account for user's height offset
  90994. if (this.isInVRMode) {
  90995. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  90996. }
  90997. else {
  90998. this._workingVector.y += this._defaultHeight;
  90999. }
  91000. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  91001. // Create animation from the camera's position to the new location
  91002. this.currentVRCamera.animations = [];
  91003. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91004. var animationCameraTeleportationKeys = [{
  91005. frame: 0,
  91006. value: this.currentVRCamera.position
  91007. },
  91008. {
  91009. frame: 11,
  91010. value: this._workingVector
  91011. }
  91012. ];
  91013. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  91014. animationCameraTeleportation.setEasingFunction(this._circleEase);
  91015. this.currentVRCamera.animations.push(animationCameraTeleportation);
  91016. this._postProcessMove.animations = [];
  91017. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91018. var vignetteWeightKeys = [];
  91019. vignetteWeightKeys.push({
  91020. frame: 0,
  91021. value: 0
  91022. });
  91023. vignetteWeightKeys.push({
  91024. frame: 5,
  91025. value: 8
  91026. });
  91027. vignetteWeightKeys.push({
  91028. frame: 11,
  91029. value: 0
  91030. });
  91031. animationPP.setKeys(vignetteWeightKeys);
  91032. this._postProcessMove.animations.push(animationPP);
  91033. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91034. var vignetteStretchKeys = [];
  91035. vignetteStretchKeys.push({
  91036. frame: 0,
  91037. value: 0
  91038. });
  91039. vignetteStretchKeys.push({
  91040. frame: 5,
  91041. value: 10
  91042. });
  91043. vignetteStretchKeys.push({
  91044. frame: 11,
  91045. value: 0
  91046. });
  91047. animationPP2.setKeys(vignetteStretchKeys);
  91048. this._postProcessMove.animations.push(animationPP2);
  91049. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91050. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91051. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91052. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  91053. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91054. });
  91055. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  91056. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  91057. });
  91058. this._hideTeleportationTarget();
  91059. };
  91060. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  91061. if (normal) {
  91062. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  91063. if (angle < Math.PI / 2) {
  91064. normal.scaleInPlace(-1);
  91065. }
  91066. }
  91067. return normal;
  91068. };
  91069. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  91070. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91071. return;
  91072. }
  91073. var ray = gazer._getForwardRay(this._rayLength);
  91074. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91075. if (hit) {
  91076. // Populate the contrllers mesh that can be used for drag/drop
  91077. if (gazer._laserPointer) {
  91078. hit.originMesh = gazer._laserPointer.parent;
  91079. }
  91080. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  91081. }
  91082. gazer._currentHit = hit;
  91083. // Moving the gazeTracker on the mesh face targetted
  91084. if (hit && hit.pickedPoint) {
  91085. if (this._displayGaze) {
  91086. var multiplier = 1;
  91087. gazer._gazeTracker.isVisible = true;
  91088. if (gazer._isActionableMesh) {
  91089. multiplier = 3;
  91090. }
  91091. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  91092. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  91093. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  91094. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  91095. // To avoid z-fighting
  91096. var deltaFighting = 0.002;
  91097. if (pickNormal) {
  91098. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91099. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91100. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  91101. }
  91102. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  91103. if (gazer._gazeTracker.position.x < 0) {
  91104. gazer._gazeTracker.position.x += deltaFighting;
  91105. }
  91106. else {
  91107. gazer._gazeTracker.position.x -= deltaFighting;
  91108. }
  91109. if (gazer._gazeTracker.position.y < 0) {
  91110. gazer._gazeTracker.position.y += deltaFighting;
  91111. }
  91112. else {
  91113. gazer._gazeTracker.position.y -= deltaFighting;
  91114. }
  91115. if (gazer._gazeTracker.position.z < 0) {
  91116. gazer._gazeTracker.position.z += deltaFighting;
  91117. }
  91118. else {
  91119. gazer._gazeTracker.position.z -= deltaFighting;
  91120. }
  91121. }
  91122. // Changing the size of the laser pointer based on the distance from the targetted point
  91123. gazer._updatePointerDistance(hit.distance);
  91124. }
  91125. else {
  91126. gazer._updatePointerDistance();
  91127. gazer._gazeTracker.isVisible = false;
  91128. }
  91129. if (hit && hit.pickedMesh) {
  91130. // The object selected is the floor, we're in a teleportation scenario
  91131. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91132. // Moving the teleportation area to this targetted point
  91133. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91134. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91135. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91136. }
  91137. gazer._currentMeshSelected = null;
  91138. if (gazer._teleportationRequestInitiated) {
  91139. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91140. }
  91141. return;
  91142. }
  91143. // If not, we're in a selection scenario
  91144. //this._teleportationAllowed = false;
  91145. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91146. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91147. this.onNewMeshPicked.notifyObservers(hit);
  91148. gazer._currentMeshSelected = hit.pickedMesh;
  91149. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91150. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91151. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91152. gazer._isActionableMesh = true;
  91153. }
  91154. else {
  91155. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91156. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91157. gazer._isActionableMesh = false;
  91158. }
  91159. try {
  91160. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91161. }
  91162. catch (err) {
  91163. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91164. }
  91165. }
  91166. else {
  91167. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91168. gazer._currentMeshSelected = null;
  91169. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91170. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91171. }
  91172. }
  91173. }
  91174. else {
  91175. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91176. gazer._currentMeshSelected = null;
  91177. //this._teleportationAllowed = false;
  91178. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91179. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91180. }
  91181. };
  91182. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91183. if (mesh) {
  91184. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91185. }
  91186. };
  91187. /**
  91188. * Sets the color of the laser ray from the vr controllers.
  91189. * @param color new color for the ray.
  91190. */
  91191. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91192. if (this.leftController) {
  91193. this.leftController._setLaserPointerColor(color);
  91194. }
  91195. if (this.rightController) {
  91196. this.rightController._setLaserPointerColor(color);
  91197. }
  91198. };
  91199. /**
  91200. * Sets the color of the ray from the vr headsets gaze.
  91201. * @param color new color for the ray.
  91202. */
  91203. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91204. if (!this._cameraGazer._gazeTracker.material) {
  91205. return;
  91206. }
  91207. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91208. if (this.leftController) {
  91209. this.leftController._gazeTracker.material.emissiveColor = color;
  91210. }
  91211. if (this.rightController) {
  91212. this.rightController._gazeTracker.material.emissiveColor = color;
  91213. }
  91214. };
  91215. /**
  91216. * Exits VR and disposes of the vr experience helper
  91217. */
  91218. VRExperienceHelper.prototype.dispose = function () {
  91219. if (this.isInVRMode) {
  91220. this.exitVR();
  91221. }
  91222. if (this._postProcessMove) {
  91223. this._postProcessMove.dispose();
  91224. }
  91225. if (this._webVRCamera) {
  91226. this._webVRCamera.dispose();
  91227. }
  91228. if (this._vrDeviceOrientationCamera) {
  91229. this._vrDeviceOrientationCamera.dispose();
  91230. }
  91231. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91232. document.body.removeChild(this._btnVR);
  91233. }
  91234. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91235. this._deviceOrientationCamera.dispose();
  91236. }
  91237. if (this._cameraGazer) {
  91238. this._cameraGazer.dispose();
  91239. }
  91240. if (this.leftController) {
  91241. this.leftController.dispose();
  91242. }
  91243. if (this.rightController) {
  91244. this.rightController.dispose();
  91245. }
  91246. if (this._teleportationTarget) {
  91247. this._teleportationTarget.dispose();
  91248. }
  91249. this._floorMeshesCollection = [];
  91250. document.removeEventListener("keydown", this._onKeyDown);
  91251. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91252. window.removeEventListener("resize", this._onResize);
  91253. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91254. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91255. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91256. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91257. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91258. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91259. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91260. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91261. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91262. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91263. this._scene.unregisterBeforeRender(this.beforeRender);
  91264. };
  91265. /**
  91266. * Gets the name of the VRExperienceHelper class
  91267. * @returns "VRExperienceHelper"
  91268. */
  91269. VRExperienceHelper.prototype.getClassName = function () {
  91270. return "VRExperienceHelper";
  91271. };
  91272. return VRExperienceHelper;
  91273. }());
  91274. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91275. })(BABYLON || (BABYLON = {}));
  91276. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91277. // Mainly based on these 2 articles :
  91278. // 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
  91279. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91280. var BABYLON;
  91281. (function (BABYLON) {
  91282. /**
  91283. * Defines the potential axis of a Joystick
  91284. */
  91285. var JoystickAxis;
  91286. (function (JoystickAxis) {
  91287. /** X axis */
  91288. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91289. /** Y axis */
  91290. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91291. /** Z axis */
  91292. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91293. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91294. /**
  91295. * Class used to define virtual joystick (used in touch mode)
  91296. */
  91297. var VirtualJoystick = /** @class */ (function () {
  91298. /**
  91299. * Creates a new virtual joystick
  91300. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91301. */
  91302. function VirtualJoystick(leftJoystick) {
  91303. var _this = this;
  91304. if (leftJoystick) {
  91305. this._leftJoystick = true;
  91306. }
  91307. else {
  91308. this._leftJoystick = false;
  91309. }
  91310. VirtualJoystick._globalJoystickIndex++;
  91311. // By default left & right arrow keys are moving the X
  91312. // and up & down keys are moving the Y
  91313. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91314. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91315. this.reverseLeftRight = false;
  91316. this.reverseUpDown = false;
  91317. // collections of pointers
  91318. this._touches = new BABYLON.StringDictionary();
  91319. this.deltaPosition = BABYLON.Vector3.Zero();
  91320. this._joystickSensibility = 25;
  91321. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91322. this._onResize = function (evt) {
  91323. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91324. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91325. if (VirtualJoystick.vjCanvas) {
  91326. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91327. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91328. }
  91329. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91330. };
  91331. // injecting a canvas element on top of the canvas 3D game
  91332. if (!VirtualJoystick.vjCanvas) {
  91333. window.addEventListener("resize", this._onResize, false);
  91334. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91335. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91336. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91337. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91338. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91339. VirtualJoystick.vjCanvas.style.width = "100%";
  91340. VirtualJoystick.vjCanvas.style.height = "100%";
  91341. VirtualJoystick.vjCanvas.style.position = "absolute";
  91342. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91343. VirtualJoystick.vjCanvas.style.top = "0px";
  91344. VirtualJoystick.vjCanvas.style.left = "0px";
  91345. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91346. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91347. // Support for jQuery PEP polyfill
  91348. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91349. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91350. if (!context) {
  91351. throw new Error("Unable to create canvas for virtual joystick");
  91352. }
  91353. VirtualJoystick.vjCanvasContext = context;
  91354. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91355. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91356. document.body.appendChild(VirtualJoystick.vjCanvas);
  91357. }
  91358. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91359. this.pressed = false;
  91360. // default joystick color
  91361. this._joystickColor = "cyan";
  91362. this._joystickPointerID = -1;
  91363. // current joystick position
  91364. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91365. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91366. // origin joystick position
  91367. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91368. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91369. this._onPointerDownHandlerRef = function (evt) {
  91370. _this._onPointerDown(evt);
  91371. };
  91372. this._onPointerMoveHandlerRef = function (evt) {
  91373. _this._onPointerMove(evt);
  91374. };
  91375. this._onPointerUpHandlerRef = function (evt) {
  91376. _this._onPointerUp(evt);
  91377. };
  91378. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91379. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91380. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91381. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91382. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91383. evt.preventDefault(); // Disables system menu
  91384. }, false);
  91385. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91386. }
  91387. /**
  91388. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91389. * @param newJoystickSensibility defines the new sensibility
  91390. */
  91391. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91392. this._joystickSensibility = newJoystickSensibility;
  91393. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91394. };
  91395. VirtualJoystick.prototype._onPointerDown = function (e) {
  91396. var positionOnScreenCondition;
  91397. e.preventDefault();
  91398. if (this._leftJoystick === true) {
  91399. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91400. }
  91401. else {
  91402. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91403. }
  91404. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91405. // First contact will be dedicated to the virtual joystick
  91406. this._joystickPointerID = e.pointerId;
  91407. this._joystickPointerStartPos.x = e.clientX;
  91408. this._joystickPointerStartPos.y = e.clientY;
  91409. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91410. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91411. this._deltaJoystickVector.x = 0;
  91412. this._deltaJoystickVector.y = 0;
  91413. this.pressed = true;
  91414. this._touches.add(e.pointerId.toString(), e);
  91415. }
  91416. else {
  91417. // You can only trigger the action buttons with a joystick declared
  91418. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91419. this._action();
  91420. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91421. }
  91422. }
  91423. };
  91424. VirtualJoystick.prototype._onPointerMove = function (e) {
  91425. // If the current pointer is the one associated to the joystick (first touch contact)
  91426. if (this._joystickPointerID == e.pointerId) {
  91427. this._joystickPointerPos.x = e.clientX;
  91428. this._joystickPointerPos.y = e.clientY;
  91429. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91430. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91431. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91432. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91433. switch (this._axisTargetedByLeftAndRight) {
  91434. case JoystickAxis.X:
  91435. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91436. break;
  91437. case JoystickAxis.Y:
  91438. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91439. break;
  91440. case JoystickAxis.Z:
  91441. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91442. break;
  91443. }
  91444. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91445. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91446. switch (this._axisTargetedByUpAndDown) {
  91447. case JoystickAxis.X:
  91448. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91449. break;
  91450. case JoystickAxis.Y:
  91451. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91452. break;
  91453. case JoystickAxis.Z:
  91454. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91455. break;
  91456. }
  91457. }
  91458. else {
  91459. var data = this._touches.get(e.pointerId.toString());
  91460. if (data) {
  91461. data.x = e.clientX;
  91462. data.y = e.clientY;
  91463. }
  91464. }
  91465. };
  91466. VirtualJoystick.prototype._onPointerUp = function (e) {
  91467. if (this._joystickPointerID == e.pointerId) {
  91468. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91469. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91470. this._joystickPointerID = -1;
  91471. this.pressed = false;
  91472. }
  91473. else {
  91474. var touch = this._touches.get(e.pointerId.toString());
  91475. if (touch) {
  91476. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91477. }
  91478. }
  91479. this._deltaJoystickVector.x = 0;
  91480. this._deltaJoystickVector.y = 0;
  91481. this._touches.remove(e.pointerId.toString());
  91482. };
  91483. /**
  91484. * Change the color of the virtual joystick
  91485. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91486. */
  91487. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91488. this._joystickColor = newColor;
  91489. };
  91490. /**
  91491. * Defines a callback to call when the joystick is touched
  91492. * @param action defines the callback
  91493. */
  91494. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91495. this._action = action;
  91496. };
  91497. /**
  91498. * Defines which axis you'd like to control for left & right
  91499. * @param axis defines the axis to use
  91500. */
  91501. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91502. switch (axis) {
  91503. case JoystickAxis.X:
  91504. case JoystickAxis.Y:
  91505. case JoystickAxis.Z:
  91506. this._axisTargetedByLeftAndRight = axis;
  91507. break;
  91508. default:
  91509. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91510. break;
  91511. }
  91512. };
  91513. /**
  91514. * Defines which axis you'd like to control for up & down
  91515. * @param axis defines the axis to use
  91516. */
  91517. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91518. switch (axis) {
  91519. case JoystickAxis.X:
  91520. case JoystickAxis.Y:
  91521. case JoystickAxis.Z:
  91522. this._axisTargetedByUpAndDown = axis;
  91523. break;
  91524. default:
  91525. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91526. break;
  91527. }
  91528. };
  91529. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91530. var _this = this;
  91531. if (this.pressed) {
  91532. this._touches.forEach(function (key, touch) {
  91533. if (touch.pointerId === _this._joystickPointerID) {
  91534. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91535. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91536. VirtualJoystick.vjCanvasContext.beginPath();
  91537. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91538. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91539. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91540. VirtualJoystick.vjCanvasContext.stroke();
  91541. VirtualJoystick.vjCanvasContext.closePath();
  91542. VirtualJoystick.vjCanvasContext.beginPath();
  91543. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91544. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91545. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91546. VirtualJoystick.vjCanvasContext.stroke();
  91547. VirtualJoystick.vjCanvasContext.closePath();
  91548. VirtualJoystick.vjCanvasContext.beginPath();
  91549. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91550. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91551. VirtualJoystick.vjCanvasContext.stroke();
  91552. VirtualJoystick.vjCanvasContext.closePath();
  91553. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91554. }
  91555. else {
  91556. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91557. VirtualJoystick.vjCanvasContext.beginPath();
  91558. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91559. VirtualJoystick.vjCanvasContext.beginPath();
  91560. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91561. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91562. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91563. VirtualJoystick.vjCanvasContext.stroke();
  91564. VirtualJoystick.vjCanvasContext.closePath();
  91565. touch.prevX = touch.x;
  91566. touch.prevY = touch.y;
  91567. }
  91568. ;
  91569. });
  91570. }
  91571. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91572. };
  91573. /**
  91574. * Release internal HTML canvas
  91575. */
  91576. VirtualJoystick.prototype.releaseCanvas = function () {
  91577. if (VirtualJoystick.vjCanvas) {
  91578. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91579. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91580. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91581. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91582. window.removeEventListener("resize", this._onResize);
  91583. document.body.removeChild(VirtualJoystick.vjCanvas);
  91584. VirtualJoystick.vjCanvas = null;
  91585. }
  91586. };
  91587. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91588. VirtualJoystick._globalJoystickIndex = 0;
  91589. return VirtualJoystick;
  91590. }());
  91591. BABYLON.VirtualJoystick = VirtualJoystick;
  91592. })(BABYLON || (BABYLON = {}));
  91593. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91594. var BABYLON;
  91595. (function (BABYLON) {
  91596. // We're mainly based on the logic defined into the FreeCamera code
  91597. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  91598. __extends(VirtualJoysticksCamera, _super);
  91599. function VirtualJoysticksCamera(name, position, scene) {
  91600. var _this = _super.call(this, name, position, scene) || this;
  91601. _this.inputs.addVirtualJoystick();
  91602. return _this;
  91603. }
  91604. VirtualJoysticksCamera.prototype.getClassName = function () {
  91605. return "VirtualJoysticksCamera";
  91606. };
  91607. return VirtualJoysticksCamera;
  91608. }(BABYLON.FreeCamera));
  91609. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  91610. })(BABYLON || (BABYLON = {}));
  91611. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  91612. var BABYLON;
  91613. (function (BABYLON) {
  91614. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  91615. function FreeCameraVirtualJoystickInput() {
  91616. }
  91617. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  91618. return this._leftjoystick;
  91619. };
  91620. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  91621. return this._rightjoystick;
  91622. };
  91623. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  91624. if (this._leftjoystick) {
  91625. var camera = this.camera;
  91626. var speed = camera._computeLocalCameraSpeed() * 50;
  91627. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  91628. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  91629. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  91630. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  91631. if (!this._leftjoystick.pressed) {
  91632. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  91633. }
  91634. if (!this._rightjoystick.pressed) {
  91635. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  91636. }
  91637. }
  91638. };
  91639. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  91640. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  91641. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  91642. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  91643. this._leftjoystick.setJoystickSensibility(0.15);
  91644. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  91645. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  91646. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  91647. this._rightjoystick.reverseUpDown = true;
  91648. this._rightjoystick.setJoystickSensibility(0.05);
  91649. this._rightjoystick.setJoystickColor("yellow");
  91650. };
  91651. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  91652. this._leftjoystick.releaseCanvas();
  91653. this._rightjoystick.releaseCanvas();
  91654. };
  91655. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  91656. return "FreeCameraVirtualJoystickInput";
  91657. };
  91658. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  91659. return "virtualJoystick";
  91660. };
  91661. return FreeCameraVirtualJoystickInput;
  91662. }());
  91663. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  91664. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  91665. })(BABYLON || (BABYLON = {}));
  91666. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  91667. var BABYLON;
  91668. (function (BABYLON) {
  91669. var SimplificationSettings = /** @class */ (function () {
  91670. function SimplificationSettings(quality, distance, optimizeMesh) {
  91671. this.quality = quality;
  91672. this.distance = distance;
  91673. this.optimizeMesh = optimizeMesh;
  91674. }
  91675. return SimplificationSettings;
  91676. }());
  91677. BABYLON.SimplificationSettings = SimplificationSettings;
  91678. var SimplificationQueue = /** @class */ (function () {
  91679. function SimplificationQueue() {
  91680. this.running = false;
  91681. this._simplificationArray = [];
  91682. }
  91683. SimplificationQueue.prototype.addTask = function (task) {
  91684. this._simplificationArray.push(task);
  91685. };
  91686. SimplificationQueue.prototype.executeNext = function () {
  91687. var task = this._simplificationArray.pop();
  91688. if (task) {
  91689. this.running = true;
  91690. this.runSimplification(task);
  91691. }
  91692. else {
  91693. this.running = false;
  91694. }
  91695. };
  91696. SimplificationQueue.prototype.runSimplification = function (task) {
  91697. var _this = this;
  91698. if (task.parallelProcessing) {
  91699. //parallel simplifier
  91700. task.settings.forEach(function (setting) {
  91701. var simplifier = _this.getSimplifier(task);
  91702. simplifier.simplify(setting, function (newMesh) {
  91703. task.mesh.addLODLevel(setting.distance, newMesh);
  91704. newMesh.isVisible = true;
  91705. //check if it is the last
  91706. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  91707. //all done, run the success callback.
  91708. task.successCallback();
  91709. }
  91710. _this.executeNext();
  91711. });
  91712. });
  91713. }
  91714. else {
  91715. //single simplifier.
  91716. var simplifier = this.getSimplifier(task);
  91717. var runDecimation = function (setting, callback) {
  91718. simplifier.simplify(setting, function (newMesh) {
  91719. task.mesh.addLODLevel(setting.distance, newMesh);
  91720. newMesh.isVisible = true;
  91721. //run the next quality level
  91722. callback();
  91723. });
  91724. };
  91725. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  91726. runDecimation(task.settings[loop.index], function () {
  91727. loop.executeNext();
  91728. });
  91729. }, function () {
  91730. //execution ended, run the success callback.
  91731. if (task.successCallback) {
  91732. task.successCallback();
  91733. }
  91734. _this.executeNext();
  91735. });
  91736. }
  91737. };
  91738. SimplificationQueue.prototype.getSimplifier = function (task) {
  91739. switch (task.simplificationType) {
  91740. case SimplificationType.QUADRATIC:
  91741. default:
  91742. return new QuadraticErrorSimplification(task.mesh);
  91743. }
  91744. };
  91745. return SimplificationQueue;
  91746. }());
  91747. BABYLON.SimplificationQueue = SimplificationQueue;
  91748. /**
  91749. * The implemented types of simplification
  91750. * At the moment only Quadratic Error Decimation is implemented
  91751. */
  91752. var SimplificationType;
  91753. (function (SimplificationType) {
  91754. /** Quadratic error decimation */
  91755. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  91756. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  91757. var DecimationTriangle = /** @class */ (function () {
  91758. function DecimationTriangle(vertices) {
  91759. this.vertices = vertices;
  91760. this.error = new Array(4);
  91761. this.deleted = false;
  91762. this.isDirty = false;
  91763. this.deletePending = false;
  91764. this.borderFactor = 0;
  91765. }
  91766. return DecimationTriangle;
  91767. }());
  91768. BABYLON.DecimationTriangle = DecimationTriangle;
  91769. var DecimationVertex = /** @class */ (function () {
  91770. function DecimationVertex(position, id) {
  91771. this.position = position;
  91772. this.id = id;
  91773. this.isBorder = true;
  91774. this.q = new QuadraticMatrix();
  91775. this.triangleCount = 0;
  91776. this.triangleStart = 0;
  91777. this.originalOffsets = [];
  91778. }
  91779. DecimationVertex.prototype.updatePosition = function (newPosition) {
  91780. this.position.copyFrom(newPosition);
  91781. };
  91782. return DecimationVertex;
  91783. }());
  91784. BABYLON.DecimationVertex = DecimationVertex;
  91785. var QuadraticMatrix = /** @class */ (function () {
  91786. function QuadraticMatrix(data) {
  91787. this.data = new Array(10);
  91788. for (var i = 0; i < 10; ++i) {
  91789. if (data && data[i]) {
  91790. this.data[i] = data[i];
  91791. }
  91792. else {
  91793. this.data[i] = 0;
  91794. }
  91795. }
  91796. }
  91797. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  91798. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  91799. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  91800. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  91801. return det;
  91802. };
  91803. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  91804. for (var i = 0; i < 10; ++i) {
  91805. this.data[i] += matrix.data[i];
  91806. }
  91807. };
  91808. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  91809. for (var i = 0; i < 10; ++i) {
  91810. this.data[i] += data[i];
  91811. }
  91812. };
  91813. QuadraticMatrix.prototype.add = function (matrix) {
  91814. var m = new QuadraticMatrix();
  91815. for (var i = 0; i < 10; ++i) {
  91816. m.data[i] = this.data[i] + matrix.data[i];
  91817. }
  91818. return m;
  91819. };
  91820. QuadraticMatrix.FromData = function (a, b, c, d) {
  91821. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  91822. };
  91823. //returning an array to avoid garbage collection
  91824. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  91825. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  91826. };
  91827. return QuadraticMatrix;
  91828. }());
  91829. BABYLON.QuadraticMatrix = QuadraticMatrix;
  91830. var Reference = /** @class */ (function () {
  91831. function Reference(vertexId, triangleId) {
  91832. this.vertexId = vertexId;
  91833. this.triangleId = triangleId;
  91834. }
  91835. return Reference;
  91836. }());
  91837. BABYLON.Reference = Reference;
  91838. /**
  91839. * An implementation of the Quadratic Error simplification algorithm.
  91840. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  91841. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  91842. * @author RaananW
  91843. */
  91844. var QuadraticErrorSimplification = /** @class */ (function () {
  91845. function QuadraticErrorSimplification(_mesh) {
  91846. this._mesh = _mesh;
  91847. this.syncIterations = 5000;
  91848. this.aggressiveness = 7;
  91849. this.decimationIterations = 100;
  91850. this.boundingBoxEpsilon = BABYLON.Epsilon;
  91851. }
  91852. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  91853. var _this = this;
  91854. this.initDecimatedMesh();
  91855. //iterating through the submeshes array, one after the other.
  91856. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  91857. _this.initWithMesh(loop.index, function () {
  91858. _this.runDecimation(settings, loop.index, function () {
  91859. loop.executeNext();
  91860. });
  91861. }, settings.optimizeMesh);
  91862. }, function () {
  91863. setTimeout(function () {
  91864. successCallback(_this._reconstructedMesh);
  91865. }, 0);
  91866. });
  91867. };
  91868. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  91869. var _this = this;
  91870. var targetCount = ~~(this.triangles.length * settings.quality);
  91871. var deletedTriangles = 0;
  91872. var triangleCount = this.triangles.length;
  91873. var iterationFunction = function (iteration, callback) {
  91874. setTimeout(function () {
  91875. if (iteration % 5 === 0) {
  91876. _this.updateMesh(iteration === 0);
  91877. }
  91878. for (var i = 0; i < _this.triangles.length; ++i) {
  91879. _this.triangles[i].isDirty = false;
  91880. }
  91881. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  91882. var trianglesIterator = function (i) {
  91883. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  91884. var t = _this.triangles[tIdx];
  91885. if (!t)
  91886. return;
  91887. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  91888. return;
  91889. }
  91890. for (var j = 0; j < 3; ++j) {
  91891. if (t.error[j] < threshold) {
  91892. var deleted0 = [];
  91893. var deleted1 = [];
  91894. var v0 = t.vertices[j];
  91895. var v1 = t.vertices[(j + 1) % 3];
  91896. if (v0.isBorder || v1.isBorder)
  91897. continue;
  91898. var p = BABYLON.Vector3.Zero();
  91899. var n = BABYLON.Vector3.Zero();
  91900. var uv = BABYLON.Vector2.Zero();
  91901. var color = new BABYLON.Color4(0, 0, 0, 1);
  91902. _this.calculateError(v0, v1, p, n, uv, color);
  91903. var delTr = new Array();
  91904. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  91905. continue;
  91906. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  91907. continue;
  91908. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  91909. continue;
  91910. var uniqueArray = new Array();
  91911. delTr.forEach(function (deletedT) {
  91912. if (uniqueArray.indexOf(deletedT) === -1) {
  91913. deletedT.deletePending = true;
  91914. uniqueArray.push(deletedT);
  91915. }
  91916. });
  91917. if (uniqueArray.length % 2 !== 0) {
  91918. continue;
  91919. }
  91920. v0.q = v1.q.add(v0.q);
  91921. v0.updatePosition(p);
  91922. var tStart = _this.references.length;
  91923. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  91924. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  91925. var tCount = _this.references.length - tStart;
  91926. if (tCount <= v0.triangleCount) {
  91927. if (tCount) {
  91928. for (var c = 0; c < tCount; c++) {
  91929. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  91930. }
  91931. }
  91932. }
  91933. else {
  91934. v0.triangleStart = tStart;
  91935. }
  91936. v0.triangleCount = tCount;
  91937. break;
  91938. }
  91939. }
  91940. };
  91941. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  91942. }, 0);
  91943. };
  91944. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  91945. if (triangleCount - deletedTriangles <= targetCount)
  91946. loop.breakLoop();
  91947. else {
  91948. iterationFunction(loop.index, function () {
  91949. loop.executeNext();
  91950. });
  91951. }
  91952. }, function () {
  91953. setTimeout(function () {
  91954. //reconstruct this part of the mesh
  91955. _this.reconstructMesh(submeshIndex);
  91956. successCallback();
  91957. }, 0);
  91958. });
  91959. };
  91960. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  91961. var _this = this;
  91962. this.vertices = [];
  91963. this.triangles = [];
  91964. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91965. var indices = this._mesh.getIndices();
  91966. var submesh = this._mesh.subMeshes[submeshIndex];
  91967. var findInVertices = function (positionToSearch) {
  91968. if (optimizeMesh) {
  91969. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  91970. if (_this.vertices[ii].position.equals(positionToSearch)) {
  91971. return _this.vertices[ii];
  91972. }
  91973. }
  91974. }
  91975. return null;
  91976. };
  91977. var vertexReferences = [];
  91978. var vertexInit = function (i) {
  91979. if (!positionData) {
  91980. return;
  91981. }
  91982. var offset = i + submesh.verticesStart;
  91983. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  91984. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  91985. vertex.originalOffsets.push(offset);
  91986. if (vertex.id === _this.vertices.length) {
  91987. _this.vertices.push(vertex);
  91988. }
  91989. vertexReferences.push(vertex.id);
  91990. };
  91991. //var totalVertices = mesh.getTotalVertices();
  91992. var totalVertices = submesh.verticesCount;
  91993. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  91994. var indicesInit = function (i) {
  91995. if (!indices) {
  91996. return;
  91997. }
  91998. var offset = (submesh.indexStart / 3) + i;
  91999. var pos = (offset * 3);
  92000. var i0 = indices[pos + 0];
  92001. var i1 = indices[pos + 1];
  92002. var i2 = indices[pos + 2];
  92003. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  92004. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  92005. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  92006. var triangle = new DecimationTriangle([v0, v1, v2]);
  92007. triangle.originalOffset = pos;
  92008. _this.triangles.push(triangle);
  92009. };
  92010. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  92011. _this.init(callback);
  92012. });
  92013. });
  92014. };
  92015. QuadraticErrorSimplification.prototype.init = function (callback) {
  92016. var _this = this;
  92017. var triangleInit1 = function (i) {
  92018. var t = _this.triangles[i];
  92019. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  92020. for (var j = 0; j < 3; j++) {
  92021. 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))));
  92022. }
  92023. };
  92024. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  92025. var triangleInit2 = function (i) {
  92026. var t = _this.triangles[i];
  92027. for (var j = 0; j < 3; ++j) {
  92028. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  92029. }
  92030. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92031. };
  92032. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  92033. callback();
  92034. });
  92035. });
  92036. };
  92037. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  92038. var newTriangles = [];
  92039. var i;
  92040. for (i = 0; i < this.vertices.length; ++i) {
  92041. this.vertices[i].triangleCount = 0;
  92042. }
  92043. var t;
  92044. var j;
  92045. for (i = 0; i < this.triangles.length; ++i) {
  92046. if (!this.triangles[i].deleted) {
  92047. t = this.triangles[i];
  92048. for (j = 0; j < 3; ++j) {
  92049. t.vertices[j].triangleCount = 1;
  92050. }
  92051. newTriangles.push(t);
  92052. }
  92053. }
  92054. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  92055. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  92056. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  92057. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  92058. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  92059. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92060. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  92061. var vertexCount = 0;
  92062. for (i = 0; i < this.vertices.length; ++i) {
  92063. var vertex = this.vertices[i];
  92064. vertex.id = vertexCount;
  92065. if (vertex.triangleCount) {
  92066. vertex.originalOffsets.forEach(function (originalOffset) {
  92067. if (!normalData) {
  92068. return;
  92069. }
  92070. newPositionData.push(vertex.position.x);
  92071. newPositionData.push(vertex.position.y);
  92072. newPositionData.push(vertex.position.z);
  92073. newNormalData.push(normalData[originalOffset * 3]);
  92074. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  92075. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  92076. if (uvs && uvs.length) {
  92077. newUVsData.push(uvs[(originalOffset * 2)]);
  92078. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  92079. }
  92080. else if (colorsData && colorsData.length) {
  92081. newColorsData.push(colorsData[(originalOffset * 4)]);
  92082. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  92083. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  92084. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  92085. }
  92086. ++vertexCount;
  92087. });
  92088. }
  92089. }
  92090. var startingIndex = this._reconstructedMesh.getTotalIndices();
  92091. var startingVertex = this._reconstructedMesh.getTotalVertices();
  92092. var submeshesArray = this._reconstructedMesh.subMeshes;
  92093. this._reconstructedMesh.subMeshes = [];
  92094. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  92095. var originalIndices = this._mesh.getIndices();
  92096. for (i = 0; i < newTriangles.length; ++i) {
  92097. t = newTriangles[i]; //now get the new referencing point for each vertex
  92098. [0, 1, 2].forEach(function (idx) {
  92099. var id = originalIndices[t.originalOffset + idx];
  92100. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  92101. if (offset < 0)
  92102. offset = 0;
  92103. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  92104. });
  92105. }
  92106. //overwriting the old vertex buffers and indices.
  92107. this._reconstructedMesh.setIndices(newIndicesArray);
  92108. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92109. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92110. if (newUVsData.length > 0)
  92111. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92112. if (newColorsData.length > 0)
  92113. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92114. //create submesh
  92115. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92116. if (submeshIndex > 0) {
  92117. this._reconstructedMesh.subMeshes = [];
  92118. submeshesArray.forEach(function (submesh) {
  92119. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92120. });
  92121. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92122. }
  92123. };
  92124. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92125. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92126. this._reconstructedMesh.material = this._mesh.material;
  92127. this._reconstructedMesh.parent = this._mesh.parent;
  92128. this._reconstructedMesh.isVisible = false;
  92129. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92130. };
  92131. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92132. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92133. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92134. if (t.deleted)
  92135. continue;
  92136. var s = this.references[vertex1.triangleStart + i].vertexId;
  92137. var v1 = t.vertices[(s + 1) % 3];
  92138. var v2 = t.vertices[(s + 2) % 3];
  92139. if ((v1 === vertex2 || v2 === vertex2)) {
  92140. deletedArray[i] = true;
  92141. delTr.push(t);
  92142. continue;
  92143. }
  92144. var d1 = v1.position.subtract(point);
  92145. d1 = d1.normalize();
  92146. var d2 = v2.position.subtract(point);
  92147. d2 = d2.normalize();
  92148. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92149. return true;
  92150. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92151. deletedArray[i] = false;
  92152. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92153. return true;
  92154. }
  92155. return false;
  92156. };
  92157. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92158. var newDeleted = deletedTriangles;
  92159. for (var i = 0; i < vertex.triangleCount; ++i) {
  92160. var ref = this.references[vertex.triangleStart + i];
  92161. var t = this.triangles[ref.triangleId];
  92162. if (t.deleted)
  92163. continue;
  92164. if (deletedArray[i] && t.deletePending) {
  92165. t.deleted = true;
  92166. newDeleted++;
  92167. continue;
  92168. }
  92169. t.vertices[ref.vertexId] = origVertex;
  92170. t.isDirty = true;
  92171. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92172. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92173. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92174. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92175. this.references.push(ref);
  92176. }
  92177. return newDeleted;
  92178. };
  92179. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92180. for (var i = 0; i < this.vertices.length; ++i) {
  92181. var vCount = [];
  92182. var vId = [];
  92183. var v = this.vertices[i];
  92184. var j;
  92185. for (j = 0; j < v.triangleCount; ++j) {
  92186. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92187. for (var ii = 0; ii < 3; ii++) {
  92188. var ofs = 0;
  92189. var vv = triangle.vertices[ii];
  92190. while (ofs < vCount.length) {
  92191. if (vId[ofs] === vv.id)
  92192. break;
  92193. ++ofs;
  92194. }
  92195. if (ofs === vCount.length) {
  92196. vCount.push(1);
  92197. vId.push(vv.id);
  92198. }
  92199. else {
  92200. vCount[ofs]++;
  92201. }
  92202. }
  92203. }
  92204. for (j = 0; j < vCount.length; ++j) {
  92205. if (vCount[j] === 1) {
  92206. this.vertices[vId[j]].isBorder = true;
  92207. }
  92208. else {
  92209. this.vertices[vId[j]].isBorder = false;
  92210. }
  92211. }
  92212. }
  92213. };
  92214. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92215. if (identifyBorders === void 0) { identifyBorders = false; }
  92216. var i;
  92217. if (!identifyBorders) {
  92218. var newTrianglesVector = [];
  92219. for (i = 0; i < this.triangles.length; ++i) {
  92220. if (!this.triangles[i].deleted) {
  92221. newTrianglesVector.push(this.triangles[i]);
  92222. }
  92223. }
  92224. this.triangles = newTrianglesVector;
  92225. }
  92226. for (i = 0; i < this.vertices.length; ++i) {
  92227. this.vertices[i].triangleCount = 0;
  92228. this.vertices[i].triangleStart = 0;
  92229. }
  92230. var t;
  92231. var j;
  92232. var v;
  92233. for (i = 0; i < this.triangles.length; ++i) {
  92234. t = this.triangles[i];
  92235. for (j = 0; j < 3; ++j) {
  92236. v = t.vertices[j];
  92237. v.triangleCount++;
  92238. }
  92239. }
  92240. var tStart = 0;
  92241. for (i = 0; i < this.vertices.length; ++i) {
  92242. this.vertices[i].triangleStart = tStart;
  92243. tStart += this.vertices[i].triangleCount;
  92244. this.vertices[i].triangleCount = 0;
  92245. }
  92246. var newReferences = new Array(this.triangles.length * 3);
  92247. for (i = 0; i < this.triangles.length; ++i) {
  92248. t = this.triangles[i];
  92249. for (j = 0; j < 3; ++j) {
  92250. v = t.vertices[j];
  92251. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92252. v.triangleCount++;
  92253. }
  92254. }
  92255. this.references = newReferences;
  92256. if (identifyBorders) {
  92257. this.identifyBorder();
  92258. }
  92259. };
  92260. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92261. var x = point.x;
  92262. var y = point.y;
  92263. var z = point.z;
  92264. 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
  92265. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92266. };
  92267. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92268. var q = vertex1.q.add(vertex2.q);
  92269. var border = vertex1.isBorder && vertex2.isBorder;
  92270. var error = 0;
  92271. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92272. if (qDet !== 0 && !border) {
  92273. if (!pointResult) {
  92274. pointResult = BABYLON.Vector3.Zero();
  92275. }
  92276. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92277. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92278. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92279. error = this.vertexError(q, pointResult);
  92280. }
  92281. else {
  92282. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92283. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92284. var error1 = this.vertexError(q, vertex1.position);
  92285. var error2 = this.vertexError(q, vertex2.position);
  92286. var error3 = this.vertexError(q, p3);
  92287. error = Math.min(error1, error2, error3);
  92288. if (error === error1) {
  92289. if (pointResult) {
  92290. pointResult.copyFrom(vertex1.position);
  92291. }
  92292. }
  92293. else if (error === error2) {
  92294. if (pointResult) {
  92295. pointResult.copyFrom(vertex2.position);
  92296. }
  92297. }
  92298. else {
  92299. if (pointResult) {
  92300. pointResult.copyFrom(p3);
  92301. }
  92302. }
  92303. }
  92304. return error;
  92305. };
  92306. return QuadraticErrorSimplification;
  92307. }());
  92308. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92309. })(BABYLON || (BABYLON = {}));
  92310. //# sourceMappingURL=babylon.meshSimplification.js.map
  92311. var BABYLON;
  92312. (function (BABYLON) {
  92313. var MeshLODLevel = /** @class */ (function () {
  92314. function MeshLODLevel(distance, mesh) {
  92315. this.distance = distance;
  92316. this.mesh = mesh;
  92317. }
  92318. return MeshLODLevel;
  92319. }());
  92320. BABYLON.MeshLODLevel = MeshLODLevel;
  92321. })(BABYLON || (BABYLON = {}));
  92322. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92323. var BABYLON;
  92324. (function (BABYLON) {
  92325. /**
  92326. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92327. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92328. */
  92329. var SceneOptimization = /** @class */ (function () {
  92330. /**
  92331. * Creates the SceneOptimization object
  92332. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92333. * @param desc defines the description associated with the optimization
  92334. */
  92335. function SceneOptimization(
  92336. /**
  92337. * Defines the priority of this optimization (0 by default which means first in the list)
  92338. */
  92339. priority) {
  92340. if (priority === void 0) { priority = 0; }
  92341. this.priority = priority;
  92342. }
  92343. /**
  92344. * Gets a string describing the action executed by the current optimization
  92345. * @returns description string
  92346. */
  92347. SceneOptimization.prototype.getDescription = function () {
  92348. return "";
  92349. };
  92350. /**
  92351. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92352. * @param scene defines the current scene where to apply this optimization
  92353. * @param optimizer defines the current optimizer
  92354. * @returns true if everything that can be done was applied
  92355. */
  92356. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92357. return true;
  92358. };
  92359. ;
  92360. return SceneOptimization;
  92361. }());
  92362. BABYLON.SceneOptimization = SceneOptimization;
  92363. /**
  92364. * Defines an optimization used to reduce the size of render target textures
  92365. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92366. */
  92367. var TextureOptimization = /** @class */ (function (_super) {
  92368. __extends(TextureOptimization, _super);
  92369. /**
  92370. * Creates the TextureOptimization object
  92371. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92372. * @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
  92373. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92374. */
  92375. function TextureOptimization(
  92376. /**
  92377. * Defines the priority of this optimization (0 by default which means first in the list)
  92378. */
  92379. priority,
  92380. /**
  92381. * 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
  92382. */
  92383. maximumSize,
  92384. /**
  92385. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92386. */
  92387. step) {
  92388. if (priority === void 0) { priority = 0; }
  92389. if (maximumSize === void 0) { maximumSize = 1024; }
  92390. if (step === void 0) { step = 0.5; }
  92391. var _this = _super.call(this, priority) || this;
  92392. _this.priority = priority;
  92393. _this.maximumSize = maximumSize;
  92394. _this.step = step;
  92395. return _this;
  92396. }
  92397. /**
  92398. * Gets a string describing the action executed by the current optimization
  92399. * @returns description string
  92400. */
  92401. TextureOptimization.prototype.getDescription = function () {
  92402. return "Reducing render target texture size to " + this.maximumSize;
  92403. };
  92404. /**
  92405. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92406. * @param scene defines the current scene where to apply this optimization
  92407. * @param optimizer defines the current optimizer
  92408. * @returns true if everything that can be done was applied
  92409. */
  92410. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92411. var allDone = true;
  92412. for (var index = 0; index < scene.textures.length; index++) {
  92413. var texture = scene.textures[index];
  92414. if (!texture.canRescale || texture.getContext) {
  92415. continue;
  92416. }
  92417. var currentSize = texture.getSize();
  92418. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92419. if (maxDimension > this.maximumSize) {
  92420. texture.scale(this.step);
  92421. allDone = false;
  92422. }
  92423. }
  92424. return allDone;
  92425. };
  92426. return TextureOptimization;
  92427. }(SceneOptimization));
  92428. BABYLON.TextureOptimization = TextureOptimization;
  92429. /**
  92430. * Defines an optimization used to increase or decrease the rendering resolution
  92431. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92432. */
  92433. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92434. __extends(HardwareScalingOptimization, _super);
  92435. /**
  92436. * Creates the HardwareScalingOptimization object
  92437. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92438. * @param maximumScale defines the maximum scale to use (2 by default)
  92439. * @param step defines the step to use between two passes (0.5 by default)
  92440. */
  92441. function HardwareScalingOptimization(
  92442. /**
  92443. * Defines the priority of this optimization (0 by default which means first in the list)
  92444. */
  92445. priority,
  92446. /**
  92447. * Defines the maximum scale to use (2 by default)
  92448. */
  92449. maximumScale,
  92450. /**
  92451. * Defines the step to use between two passes (0.5 by default)
  92452. */
  92453. step) {
  92454. if (priority === void 0) { priority = 0; }
  92455. if (maximumScale === void 0) { maximumScale = 2; }
  92456. if (step === void 0) { step = 0.25; }
  92457. var _this = _super.call(this, priority) || this;
  92458. _this.priority = priority;
  92459. _this.maximumScale = maximumScale;
  92460. _this.step = step;
  92461. _this._currentScale = -1;
  92462. _this._directionOffset = 1;
  92463. return _this;
  92464. }
  92465. /**
  92466. * Gets a string describing the action executed by the current optimization
  92467. * @return description string
  92468. */
  92469. HardwareScalingOptimization.prototype.getDescription = function () {
  92470. return "Setting hardware scaling level to " + this._currentScale;
  92471. };
  92472. /**
  92473. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92474. * @param scene defines the current scene where to apply this optimization
  92475. * @param optimizer defines the current optimizer
  92476. * @returns true if everything that can be done was applied
  92477. */
  92478. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92479. if (this._currentScale === -1) {
  92480. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92481. if (this._currentScale > this.maximumScale) {
  92482. this._directionOffset = -1;
  92483. }
  92484. }
  92485. this._currentScale += this._directionOffset * this.step;
  92486. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92487. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92488. };
  92489. ;
  92490. return HardwareScalingOptimization;
  92491. }(SceneOptimization));
  92492. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92493. /**
  92494. * Defines an optimization used to remove shadows
  92495. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92496. */
  92497. var ShadowsOptimization = /** @class */ (function (_super) {
  92498. __extends(ShadowsOptimization, _super);
  92499. function ShadowsOptimization() {
  92500. return _super !== null && _super.apply(this, arguments) || this;
  92501. }
  92502. /**
  92503. * Gets a string describing the action executed by the current optimization
  92504. * @return description string
  92505. */
  92506. ShadowsOptimization.prototype.getDescription = function () {
  92507. return "Turning shadows on/off";
  92508. };
  92509. /**
  92510. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92511. * @param scene defines the current scene where to apply this optimization
  92512. * @param optimizer defines the current optimizer
  92513. * @returns true if everything that can be done was applied
  92514. */
  92515. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92516. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92517. return true;
  92518. };
  92519. ;
  92520. return ShadowsOptimization;
  92521. }(SceneOptimization));
  92522. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92523. /**
  92524. * Defines an optimization used to turn post-processes off
  92525. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92526. */
  92527. var PostProcessesOptimization = /** @class */ (function (_super) {
  92528. __extends(PostProcessesOptimization, _super);
  92529. function PostProcessesOptimization() {
  92530. return _super !== null && _super.apply(this, arguments) || this;
  92531. }
  92532. /**
  92533. * Gets a string describing the action executed by the current optimization
  92534. * @return description string
  92535. */
  92536. PostProcessesOptimization.prototype.getDescription = function () {
  92537. return "Turning post-processes on/off";
  92538. };
  92539. /**
  92540. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92541. * @param scene defines the current scene where to apply this optimization
  92542. * @param optimizer defines the current optimizer
  92543. * @returns true if everything that can be done was applied
  92544. */
  92545. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92546. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92547. return true;
  92548. };
  92549. ;
  92550. return PostProcessesOptimization;
  92551. }(SceneOptimization));
  92552. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92553. /**
  92554. * Defines an optimization used to turn lens flares off
  92555. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92556. */
  92557. var LensFlaresOptimization = /** @class */ (function (_super) {
  92558. __extends(LensFlaresOptimization, _super);
  92559. function LensFlaresOptimization() {
  92560. return _super !== null && _super.apply(this, arguments) || this;
  92561. }
  92562. /**
  92563. * Gets a string describing the action executed by the current optimization
  92564. * @return description string
  92565. */
  92566. LensFlaresOptimization.prototype.getDescription = function () {
  92567. return "Turning lens flares on/off";
  92568. };
  92569. /**
  92570. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92571. * @param scene defines the current scene where to apply this optimization
  92572. * @param optimizer defines the current optimizer
  92573. * @returns true if everything that can be done was applied
  92574. */
  92575. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92576. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92577. return true;
  92578. };
  92579. ;
  92580. return LensFlaresOptimization;
  92581. }(SceneOptimization));
  92582. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92583. /**
  92584. * Defines an optimization based on user defined callback.
  92585. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92586. */
  92587. var CustomOptimization = /** @class */ (function (_super) {
  92588. __extends(CustomOptimization, _super);
  92589. function CustomOptimization() {
  92590. return _super !== null && _super.apply(this, arguments) || this;
  92591. }
  92592. /**
  92593. * Gets a string describing the action executed by the current optimization
  92594. * @returns description string
  92595. */
  92596. CustomOptimization.prototype.getDescription = function () {
  92597. if (this.onGetDescription) {
  92598. return this.onGetDescription();
  92599. }
  92600. return "Running user defined callback";
  92601. };
  92602. /**
  92603. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92604. * @param scene defines the current scene where to apply this optimization
  92605. * @param optimizer defines the current optimizer
  92606. * @returns true if everything that can be done was applied
  92607. */
  92608. CustomOptimization.prototype.apply = function (scene, optimizer) {
  92609. if (this.onApply) {
  92610. return this.onApply(scene, optimizer);
  92611. }
  92612. return true;
  92613. };
  92614. ;
  92615. return CustomOptimization;
  92616. }(SceneOptimization));
  92617. BABYLON.CustomOptimization = CustomOptimization;
  92618. /**
  92619. * Defines an optimization used to turn particles off
  92620. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92621. */
  92622. var ParticlesOptimization = /** @class */ (function (_super) {
  92623. __extends(ParticlesOptimization, _super);
  92624. function ParticlesOptimization() {
  92625. return _super !== null && _super.apply(this, arguments) || this;
  92626. }
  92627. /**
  92628. * Gets a string describing the action executed by the current optimization
  92629. * @return description string
  92630. */
  92631. ParticlesOptimization.prototype.getDescription = function () {
  92632. return "Turning particles on/off";
  92633. };
  92634. /**
  92635. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92636. * @param scene defines the current scene where to apply this optimization
  92637. * @param optimizer defines the current optimizer
  92638. * @returns true if everything that can be done was applied
  92639. */
  92640. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  92641. scene.particlesEnabled = optimizer.isInImprovementMode;
  92642. return true;
  92643. };
  92644. ;
  92645. return ParticlesOptimization;
  92646. }(SceneOptimization));
  92647. BABYLON.ParticlesOptimization = ParticlesOptimization;
  92648. /**
  92649. * Defines an optimization used to turn render targets off
  92650. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92651. */
  92652. var RenderTargetsOptimization = /** @class */ (function (_super) {
  92653. __extends(RenderTargetsOptimization, _super);
  92654. function RenderTargetsOptimization() {
  92655. return _super !== null && _super.apply(this, arguments) || this;
  92656. }
  92657. /**
  92658. * Gets a string describing the action executed by the current optimization
  92659. * @return description string
  92660. */
  92661. RenderTargetsOptimization.prototype.getDescription = function () {
  92662. return "Turning render targets off";
  92663. };
  92664. /**
  92665. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92666. * @param scene defines the current scene where to apply this optimization
  92667. * @param optimizer defines the current optimizer
  92668. * @returns true if everything that can be done was applied
  92669. */
  92670. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  92671. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  92672. return true;
  92673. };
  92674. ;
  92675. return RenderTargetsOptimization;
  92676. }(SceneOptimization));
  92677. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  92678. /**
  92679. * Defines an optimization used to merge meshes with compatible materials
  92680. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92681. */
  92682. var MergeMeshesOptimization = /** @class */ (function (_super) {
  92683. __extends(MergeMeshesOptimization, _super);
  92684. function MergeMeshesOptimization() {
  92685. var _this = _super !== null && _super.apply(this, arguments) || this;
  92686. _this._canBeMerged = function (abstractMesh) {
  92687. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  92688. return false;
  92689. }
  92690. var mesh = abstractMesh;
  92691. if (!mesh.isVisible || !mesh.isEnabled()) {
  92692. return false;
  92693. }
  92694. if (mesh.instances.length > 0) {
  92695. return false;
  92696. }
  92697. if (mesh.skeleton || mesh.hasLODLevels) {
  92698. return false;
  92699. }
  92700. if (mesh.parent) {
  92701. return false;
  92702. }
  92703. return true;
  92704. };
  92705. return _this;
  92706. }
  92707. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  92708. /**
  92709. * Gets or sets a boolean which defines if optimization octree has to be updated
  92710. */
  92711. get: function () {
  92712. return MergeMeshesOptimization._UpdateSelectionTree;
  92713. },
  92714. /**
  92715. * Gets or sets a boolean which defines if optimization octree has to be updated
  92716. */
  92717. set: function (value) {
  92718. MergeMeshesOptimization._UpdateSelectionTree = value;
  92719. },
  92720. enumerable: true,
  92721. configurable: true
  92722. });
  92723. /**
  92724. * Gets a string describing the action executed by the current optimization
  92725. * @return description string
  92726. */
  92727. MergeMeshesOptimization.prototype.getDescription = function () {
  92728. return "Merging similar meshes together";
  92729. };
  92730. /**
  92731. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92732. * @param scene defines the current scene where to apply this optimization
  92733. * @param optimizer defines the current optimizer
  92734. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  92735. * @returns true if everything that can be done was applied
  92736. */
  92737. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  92738. var globalPool = scene.meshes.slice(0);
  92739. var globalLength = globalPool.length;
  92740. for (var index = 0; index < globalLength; index++) {
  92741. var currentPool = new Array();
  92742. var current = globalPool[index];
  92743. // Checks
  92744. if (!this._canBeMerged(current)) {
  92745. continue;
  92746. }
  92747. currentPool.push(current);
  92748. // Find compatible meshes
  92749. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  92750. var otherMesh = globalPool[subIndex];
  92751. if (!this._canBeMerged(otherMesh)) {
  92752. continue;
  92753. }
  92754. if (otherMesh.material !== current.material) {
  92755. continue;
  92756. }
  92757. if (otherMesh.checkCollisions !== current.checkCollisions) {
  92758. continue;
  92759. }
  92760. currentPool.push(otherMesh);
  92761. globalLength--;
  92762. globalPool.splice(subIndex, 1);
  92763. subIndex--;
  92764. }
  92765. if (currentPool.length < 2) {
  92766. continue;
  92767. }
  92768. // Merge meshes
  92769. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  92770. }
  92771. if (updateSelectionTree != undefined) {
  92772. if (updateSelectionTree) {
  92773. scene.createOrUpdateSelectionOctree();
  92774. }
  92775. }
  92776. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  92777. scene.createOrUpdateSelectionOctree();
  92778. }
  92779. return true;
  92780. };
  92781. ;
  92782. MergeMeshesOptimization._UpdateSelectionTree = false;
  92783. return MergeMeshesOptimization;
  92784. }(SceneOptimization));
  92785. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  92786. /**
  92787. * Defines a list of options used by SceneOptimizer
  92788. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92789. */
  92790. var SceneOptimizerOptions = /** @class */ (function () {
  92791. /**
  92792. * Creates a new list of options used by SceneOptimizer
  92793. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  92794. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  92795. */
  92796. function SceneOptimizerOptions(
  92797. /**
  92798. * Defines the target frame rate to reach (60 by default)
  92799. */
  92800. targetFrameRate,
  92801. /**
  92802. * Defines the interval between two checkes (2000ms by default)
  92803. */
  92804. trackerDuration) {
  92805. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  92806. if (trackerDuration === void 0) { trackerDuration = 2000; }
  92807. this.targetFrameRate = targetFrameRate;
  92808. this.trackerDuration = trackerDuration;
  92809. /**
  92810. * Gets the list of optimizations to apply
  92811. */
  92812. this.optimizations = new Array();
  92813. }
  92814. /**
  92815. * Add a new optimization
  92816. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  92817. * @returns the current SceneOptimizerOptions
  92818. */
  92819. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  92820. this.optimizations.push(optimization);
  92821. return this;
  92822. };
  92823. /**
  92824. * Add a new custom optimization
  92825. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  92826. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  92827. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92828. * @returns the current SceneOptimizerOptions
  92829. */
  92830. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  92831. if (priority === void 0) { priority = 0; }
  92832. var optimization = new CustomOptimization(priority);
  92833. optimization.onApply = onApply;
  92834. optimization.onGetDescription = onGetDescription;
  92835. this.optimizations.push(optimization);
  92836. return this;
  92837. };
  92838. /**
  92839. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  92840. * @param targetFrameRate defines the target frame rate (60 by default)
  92841. * @returns a SceneOptimizerOptions object
  92842. */
  92843. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  92844. var result = new SceneOptimizerOptions(targetFrameRate);
  92845. var priority = 0;
  92846. result.addOptimization(new MergeMeshesOptimization(priority));
  92847. result.addOptimization(new ShadowsOptimization(priority));
  92848. result.addOptimization(new LensFlaresOptimization(priority));
  92849. // Next priority
  92850. priority++;
  92851. result.addOptimization(new PostProcessesOptimization(priority));
  92852. result.addOptimization(new ParticlesOptimization(priority));
  92853. // Next priority
  92854. priority++;
  92855. result.addOptimization(new TextureOptimization(priority, 1024));
  92856. return result;
  92857. };
  92858. /**
  92859. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  92860. * @param targetFrameRate defines the target frame rate (60 by default)
  92861. * @returns a SceneOptimizerOptions object
  92862. */
  92863. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  92864. var result = new SceneOptimizerOptions(targetFrameRate);
  92865. var priority = 0;
  92866. result.addOptimization(new MergeMeshesOptimization(priority));
  92867. result.addOptimization(new ShadowsOptimization(priority));
  92868. result.addOptimization(new LensFlaresOptimization(priority));
  92869. // Next priority
  92870. priority++;
  92871. result.addOptimization(new PostProcessesOptimization(priority));
  92872. result.addOptimization(new ParticlesOptimization(priority));
  92873. // Next priority
  92874. priority++;
  92875. result.addOptimization(new TextureOptimization(priority, 512));
  92876. // Next priority
  92877. priority++;
  92878. result.addOptimization(new RenderTargetsOptimization(priority));
  92879. // Next priority
  92880. priority++;
  92881. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  92882. return result;
  92883. };
  92884. /**
  92885. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  92886. * @param targetFrameRate defines the target frame rate (60 by default)
  92887. * @returns a SceneOptimizerOptions object
  92888. */
  92889. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  92890. var result = new SceneOptimizerOptions(targetFrameRate);
  92891. var priority = 0;
  92892. result.addOptimization(new MergeMeshesOptimization(priority));
  92893. result.addOptimization(new ShadowsOptimization(priority));
  92894. result.addOptimization(new LensFlaresOptimization(priority));
  92895. // Next priority
  92896. priority++;
  92897. result.addOptimization(new PostProcessesOptimization(priority));
  92898. result.addOptimization(new ParticlesOptimization(priority));
  92899. // Next priority
  92900. priority++;
  92901. result.addOptimization(new TextureOptimization(priority, 256));
  92902. // Next priority
  92903. priority++;
  92904. result.addOptimization(new RenderTargetsOptimization(priority));
  92905. // Next priority
  92906. priority++;
  92907. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  92908. return result;
  92909. };
  92910. return SceneOptimizerOptions;
  92911. }());
  92912. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  92913. /**
  92914. * Class used to run optimizations in order to reach a target frame rate
  92915. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92916. */
  92917. var SceneOptimizer = /** @class */ (function () {
  92918. /**
  92919. * Creates a new SceneOptimizer
  92920. * @param scene defines the scene to work on
  92921. * @param options defines the options to use with the SceneOptimizer
  92922. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  92923. * @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)
  92924. */
  92925. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  92926. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  92927. if (improvementMode === void 0) { improvementMode = false; }
  92928. var _this = this;
  92929. this._isRunning = false;
  92930. this._currentPriorityLevel = 0;
  92931. this._targetFrameRate = 60;
  92932. this._trackerDuration = 2000;
  92933. this._currentFrameRate = 0;
  92934. this._improvementMode = false;
  92935. /**
  92936. * Defines an observable called when the optimizer reaches the target frame rate
  92937. */
  92938. this.onSuccessObservable = new BABYLON.Observable();
  92939. /**
  92940. * Defines an observable called when the optimizer enables an optimization
  92941. */
  92942. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  92943. /**
  92944. * Defines an observable called when the optimizer is not able to reach the target frame rate
  92945. */
  92946. this.onFailureObservable = new BABYLON.Observable();
  92947. if (!options) {
  92948. this._options = new SceneOptimizerOptions();
  92949. }
  92950. else {
  92951. this._options = options;
  92952. }
  92953. if (this._options.targetFrameRate) {
  92954. this._targetFrameRate = this._options.targetFrameRate;
  92955. }
  92956. if (this._options.trackerDuration) {
  92957. this._trackerDuration = this._options.trackerDuration;
  92958. }
  92959. if (autoGeneratePriorities) {
  92960. var priority = 0;
  92961. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  92962. var optim = _a[_i];
  92963. optim.priority = priority++;
  92964. }
  92965. }
  92966. this._improvementMode = improvementMode;
  92967. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92968. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  92969. _this._sceneDisposeObserver = null;
  92970. _this.dispose();
  92971. });
  92972. }
  92973. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  92974. /**
  92975. * Gets a boolean indicating if the optimizer is in improvement mode
  92976. */
  92977. get: function () {
  92978. return this._improvementMode;
  92979. },
  92980. enumerable: true,
  92981. configurable: true
  92982. });
  92983. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  92984. /**
  92985. * Gets the current priority level (0 at start)
  92986. */
  92987. get: function () {
  92988. return this._currentPriorityLevel;
  92989. },
  92990. enumerable: true,
  92991. configurable: true
  92992. });
  92993. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  92994. /**
  92995. * Gets the current frame rate checked by the SceneOptimizer
  92996. */
  92997. get: function () {
  92998. return this._currentFrameRate;
  92999. },
  93000. enumerable: true,
  93001. configurable: true
  93002. });
  93003. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  93004. /**
  93005. * Gets or sets the current target frame rate (60 by default)
  93006. */
  93007. get: function () {
  93008. return this._targetFrameRate;
  93009. },
  93010. /**
  93011. * Gets or sets the current target frame rate (60 by default)
  93012. */
  93013. set: function (value) {
  93014. this._targetFrameRate = value;
  93015. },
  93016. enumerable: true,
  93017. configurable: true
  93018. });
  93019. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  93020. /**
  93021. * Gets or sets the current interval between two checks (every 2000ms by default)
  93022. */
  93023. get: function () {
  93024. return this._trackerDuration;
  93025. },
  93026. /**
  93027. * Gets or sets the current interval between two checks (every 2000ms by default)
  93028. */
  93029. set: function (value) {
  93030. this._trackerDuration = value;
  93031. },
  93032. enumerable: true,
  93033. configurable: true
  93034. });
  93035. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  93036. /**
  93037. * Gets the list of active optimizations
  93038. */
  93039. get: function () {
  93040. return this._options.optimizations;
  93041. },
  93042. enumerable: true,
  93043. configurable: true
  93044. });
  93045. /**
  93046. * Stops the current optimizer
  93047. */
  93048. SceneOptimizer.prototype.stop = function () {
  93049. this._isRunning = false;
  93050. };
  93051. /**
  93052. * Reset the optimizer to initial step (current priority level = 0)
  93053. */
  93054. SceneOptimizer.prototype.reset = function () {
  93055. this._currentPriorityLevel = 0;
  93056. };
  93057. /**
  93058. * Start the optimizer. By default it will try to reach a specific framerate
  93059. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  93060. */
  93061. SceneOptimizer.prototype.start = function () {
  93062. var _this = this;
  93063. if (this._isRunning) {
  93064. return;
  93065. }
  93066. this._isRunning = true;
  93067. // Let's wait for the scene to be ready before running our check
  93068. this._scene.executeWhenReady(function () {
  93069. setTimeout(function () {
  93070. _this._checkCurrentState();
  93071. }, _this._trackerDuration);
  93072. });
  93073. };
  93074. SceneOptimizer.prototype._checkCurrentState = function () {
  93075. var _this = this;
  93076. if (!this._isRunning) {
  93077. return;
  93078. }
  93079. var scene = this._scene;
  93080. var options = this._options;
  93081. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  93082. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  93083. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  93084. this._isRunning = false;
  93085. this.onSuccessObservable.notifyObservers(this);
  93086. return;
  93087. }
  93088. // Apply current level of optimizations
  93089. var allDone = true;
  93090. var noOptimizationApplied = true;
  93091. for (var index = 0; index < options.optimizations.length; index++) {
  93092. var optimization = options.optimizations[index];
  93093. if (optimization.priority === this._currentPriorityLevel) {
  93094. noOptimizationApplied = false;
  93095. allDone = allDone && optimization.apply(scene, this);
  93096. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  93097. }
  93098. }
  93099. // If no optimization was applied, this is a failure :(
  93100. if (noOptimizationApplied) {
  93101. this._isRunning = false;
  93102. this.onFailureObservable.notifyObservers(this);
  93103. return;
  93104. }
  93105. // If all optimizations were done, move to next level
  93106. if (allDone) {
  93107. this._currentPriorityLevel++;
  93108. }
  93109. // Let's the system running for a specific amount of time before checking FPS
  93110. scene.executeWhenReady(function () {
  93111. setTimeout(function () {
  93112. _this._checkCurrentState();
  93113. }, _this._trackerDuration);
  93114. });
  93115. };
  93116. /**
  93117. * Release all resources
  93118. */
  93119. SceneOptimizer.prototype.dispose = function () {
  93120. this.stop();
  93121. this.onSuccessObservable.clear();
  93122. this.onFailureObservable.clear();
  93123. this.onNewOptimizationAppliedObservable.clear();
  93124. if (this._sceneDisposeObserver) {
  93125. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93126. }
  93127. };
  93128. /**
  93129. * Helper function to create a SceneOptimizer with one single line of code
  93130. * @param scene defines the scene to work on
  93131. * @param options defines the options to use with the SceneOptimizer
  93132. * @param onSuccess defines a callback to call on success
  93133. * @param onFailure defines a callback to call on failure
  93134. * @returns the new SceneOptimizer object
  93135. */
  93136. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93137. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93138. if (onSuccess) {
  93139. optimizer.onSuccessObservable.add(function () {
  93140. onSuccess();
  93141. });
  93142. }
  93143. if (onFailure) {
  93144. optimizer.onFailureObservable.add(function () {
  93145. onFailure();
  93146. });
  93147. }
  93148. optimizer.start();
  93149. return optimizer;
  93150. };
  93151. return SceneOptimizer;
  93152. }());
  93153. BABYLON.SceneOptimizer = SceneOptimizer;
  93154. })(BABYLON || (BABYLON = {}));
  93155. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93156. var BABYLON;
  93157. (function (BABYLON) {
  93158. var OutlineRenderer = /** @class */ (function () {
  93159. function OutlineRenderer(scene) {
  93160. this.zOffset = 1;
  93161. this._scene = scene;
  93162. }
  93163. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93164. var _this = this;
  93165. if (useOverlay === void 0) { useOverlay = false; }
  93166. var scene = this._scene;
  93167. var engine = this._scene.getEngine();
  93168. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93169. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93170. return;
  93171. }
  93172. var mesh = subMesh.getRenderingMesh();
  93173. var material = subMesh.getMaterial();
  93174. if (!material || !scene.activeCamera) {
  93175. return;
  93176. }
  93177. engine.enableEffect(this._effect);
  93178. // Logarithmic depth
  93179. if (material.useLogarithmicDepth) {
  93180. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93181. }
  93182. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93183. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93184. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93185. // Bones
  93186. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93187. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93188. }
  93189. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93190. // Alpha test
  93191. if (material && material.needAlphaTesting()) {
  93192. var alphaTexture = material.getAlphaTestTexture();
  93193. if (alphaTexture) {
  93194. this._effect.setTexture("diffuseSampler", alphaTexture);
  93195. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93196. }
  93197. }
  93198. engine.setZOffset(-this.zOffset);
  93199. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93200. engine.setZOffset(0);
  93201. };
  93202. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93203. var defines = [];
  93204. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93205. var mesh = subMesh.getMesh();
  93206. var material = subMesh.getMaterial();
  93207. if (material) {
  93208. // Alpha test
  93209. if (material.needAlphaTesting()) {
  93210. defines.push("#define ALPHATEST");
  93211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93212. attribs.push(BABYLON.VertexBuffer.UVKind);
  93213. defines.push("#define UV1");
  93214. }
  93215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93216. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93217. defines.push("#define UV2");
  93218. }
  93219. }
  93220. //Logarithmic depth
  93221. if (material.useLogarithmicDepth) {
  93222. defines.push("#define LOGARITHMICDEPTH");
  93223. }
  93224. }
  93225. // Bones
  93226. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93227. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93228. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93229. if (mesh.numBoneInfluencers > 4) {
  93230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93232. }
  93233. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93234. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93235. }
  93236. else {
  93237. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93238. }
  93239. // Instances
  93240. if (useInstances) {
  93241. defines.push("#define INSTANCES");
  93242. attribs.push("world0");
  93243. attribs.push("world1");
  93244. attribs.push("world2");
  93245. attribs.push("world3");
  93246. }
  93247. // Get correct effect
  93248. var join = defines.join("\n");
  93249. if (this._cachedDefines !== join) {
  93250. this._cachedDefines = join;
  93251. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93252. }
  93253. return this._effect.isReady();
  93254. };
  93255. return OutlineRenderer;
  93256. }());
  93257. BABYLON.OutlineRenderer = OutlineRenderer;
  93258. })(BABYLON || (BABYLON = {}));
  93259. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93260. var BABYLON;
  93261. (function (BABYLON) {
  93262. var FaceAdjacencies = /** @class */ (function () {
  93263. function FaceAdjacencies() {
  93264. this.edges = new Array();
  93265. this.edgesConnectedCount = 0;
  93266. }
  93267. return FaceAdjacencies;
  93268. }());
  93269. var EdgesRenderer = /** @class */ (function () {
  93270. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93271. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93272. if (epsilon === void 0) { epsilon = 0.95; }
  93273. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93274. this.edgesWidthScalerForOrthographic = 1000.0;
  93275. this.edgesWidthScalerForPerspective = 50.0;
  93276. this._linesPositions = new Array();
  93277. this._linesNormals = new Array();
  93278. this._linesIndices = new Array();
  93279. this._buffers = {};
  93280. this._checkVerticesInsteadOfIndices = false;
  93281. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93282. this.isEnabled = true;
  93283. this._source = source;
  93284. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93285. this._epsilon = epsilon;
  93286. this._prepareRessources();
  93287. this._generateEdgesLines();
  93288. }
  93289. EdgesRenderer.prototype._prepareRessources = function () {
  93290. if (this._lineShader) {
  93291. return;
  93292. }
  93293. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93294. attributes: ["position", "normal"],
  93295. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93296. });
  93297. this._lineShader.disableDepthWrite = true;
  93298. this._lineShader.backFaceCulling = false;
  93299. };
  93300. EdgesRenderer.prototype._rebuild = function () {
  93301. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93302. if (buffer) {
  93303. buffer._rebuild();
  93304. }
  93305. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93306. if (buffer) {
  93307. buffer._rebuild();
  93308. }
  93309. var scene = this._source.getScene();
  93310. var engine = scene.getEngine();
  93311. this._ib = engine.createIndexBuffer(this._linesIndices);
  93312. };
  93313. EdgesRenderer.prototype.dispose = function () {
  93314. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93315. if (buffer) {
  93316. buffer.dispose();
  93317. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93318. }
  93319. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93320. if (buffer) {
  93321. buffer.dispose();
  93322. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93323. }
  93324. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93325. this._lineShader.dispose();
  93326. };
  93327. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93328. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93329. return 0;
  93330. }
  93331. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93332. return 1;
  93333. }
  93334. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93335. return 2;
  93336. }
  93337. return -1;
  93338. };
  93339. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93340. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93341. return 0;
  93342. }
  93343. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93344. return 1;
  93345. }
  93346. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93347. return 2;
  93348. }
  93349. return -1;
  93350. };
  93351. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93352. var needToCreateLine;
  93353. if (edge === undefined) {
  93354. needToCreateLine = true;
  93355. }
  93356. else {
  93357. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93358. needToCreateLine = dotProduct < this._epsilon;
  93359. }
  93360. if (needToCreateLine) {
  93361. var offset = this._linesPositions.length / 3;
  93362. var normal = p0.subtract(p1);
  93363. normal.normalize();
  93364. // Positions
  93365. this._linesPositions.push(p0.x);
  93366. this._linesPositions.push(p0.y);
  93367. this._linesPositions.push(p0.z);
  93368. this._linesPositions.push(p0.x);
  93369. this._linesPositions.push(p0.y);
  93370. this._linesPositions.push(p0.z);
  93371. this._linesPositions.push(p1.x);
  93372. this._linesPositions.push(p1.y);
  93373. this._linesPositions.push(p1.z);
  93374. this._linesPositions.push(p1.x);
  93375. this._linesPositions.push(p1.y);
  93376. this._linesPositions.push(p1.z);
  93377. // Normals
  93378. this._linesNormals.push(p1.x);
  93379. this._linesNormals.push(p1.y);
  93380. this._linesNormals.push(p1.z);
  93381. this._linesNormals.push(-1);
  93382. this._linesNormals.push(p1.x);
  93383. this._linesNormals.push(p1.y);
  93384. this._linesNormals.push(p1.z);
  93385. this._linesNormals.push(1);
  93386. this._linesNormals.push(p0.x);
  93387. this._linesNormals.push(p0.y);
  93388. this._linesNormals.push(p0.z);
  93389. this._linesNormals.push(-1);
  93390. this._linesNormals.push(p0.x);
  93391. this._linesNormals.push(p0.y);
  93392. this._linesNormals.push(p0.z);
  93393. this._linesNormals.push(1);
  93394. // Indices
  93395. this._linesIndices.push(offset);
  93396. this._linesIndices.push(offset + 1);
  93397. this._linesIndices.push(offset + 2);
  93398. this._linesIndices.push(offset);
  93399. this._linesIndices.push(offset + 2);
  93400. this._linesIndices.push(offset + 3);
  93401. }
  93402. };
  93403. EdgesRenderer.prototype._generateEdgesLines = function () {
  93404. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93405. var indices = this._source.getIndices();
  93406. if (!indices || !positions) {
  93407. return;
  93408. }
  93409. // First let's find adjacencies
  93410. var adjacencies = new Array();
  93411. var faceNormals = new Array();
  93412. var index;
  93413. var faceAdjacencies;
  93414. // Prepare faces
  93415. for (index = 0; index < indices.length; index += 3) {
  93416. faceAdjacencies = new FaceAdjacencies();
  93417. var p0Index = indices[index];
  93418. var p1Index = indices[index + 1];
  93419. var p2Index = indices[index + 2];
  93420. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93421. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93422. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93423. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93424. faceNormal.normalize();
  93425. faceNormals.push(faceNormal);
  93426. adjacencies.push(faceAdjacencies);
  93427. }
  93428. // Scan
  93429. for (index = 0; index < adjacencies.length; index++) {
  93430. faceAdjacencies = adjacencies[index];
  93431. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93432. var otherFaceAdjacencies = adjacencies[otherIndex];
  93433. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93434. break;
  93435. }
  93436. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93437. continue;
  93438. }
  93439. var otherP0 = indices[otherIndex * 3];
  93440. var otherP1 = indices[otherIndex * 3 + 1];
  93441. var otherP2 = indices[otherIndex * 3 + 2];
  93442. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93443. var otherEdgeIndex = 0;
  93444. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93445. continue;
  93446. }
  93447. switch (edgeIndex) {
  93448. case 0:
  93449. if (this._checkVerticesInsteadOfIndices) {
  93450. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93451. }
  93452. else {
  93453. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93454. }
  93455. break;
  93456. case 1:
  93457. if (this._checkVerticesInsteadOfIndices) {
  93458. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93459. }
  93460. else {
  93461. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93462. }
  93463. break;
  93464. case 2:
  93465. if (this._checkVerticesInsteadOfIndices) {
  93466. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93467. }
  93468. else {
  93469. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93470. }
  93471. break;
  93472. }
  93473. if (otherEdgeIndex === -1) {
  93474. continue;
  93475. }
  93476. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93477. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93478. faceAdjacencies.edgesConnectedCount++;
  93479. otherFaceAdjacencies.edgesConnectedCount++;
  93480. if (faceAdjacencies.edgesConnectedCount === 3) {
  93481. break;
  93482. }
  93483. }
  93484. }
  93485. }
  93486. // Create lines
  93487. for (index = 0; index < adjacencies.length; index++) {
  93488. // 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
  93489. var current = adjacencies[index];
  93490. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93491. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93492. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93493. }
  93494. // Merge into a single mesh
  93495. var engine = this._source.getScene().getEngine();
  93496. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93497. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93498. this._ib = engine.createIndexBuffer(this._linesIndices);
  93499. this._indicesCount = this._linesIndices.length;
  93500. };
  93501. EdgesRenderer.prototype.render = function () {
  93502. var scene = this._source.getScene();
  93503. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93504. return;
  93505. }
  93506. var engine = scene.getEngine();
  93507. this._lineShader._preBind();
  93508. // VBOs
  93509. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93510. scene.resetCachedMaterial();
  93511. this._lineShader.setColor4("color", this._source.edgesColor);
  93512. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93513. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93514. }
  93515. else {
  93516. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93517. }
  93518. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93519. this._lineShader.bind(this._source.getWorldMatrix());
  93520. // Draw order
  93521. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93522. this._lineShader.unbind();
  93523. engine.setDepthWrite(true);
  93524. };
  93525. return EdgesRenderer;
  93526. }());
  93527. BABYLON.EdgesRenderer = EdgesRenderer;
  93528. })(BABYLON || (BABYLON = {}));
  93529. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93530. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93531. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93532. s = arguments[i];
  93533. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93534. t[p] = s[p];
  93535. }
  93536. return t;
  93537. };
  93538. var BABYLON;
  93539. (function (BABYLON) {
  93540. /**
  93541. * The effect layer Helps adding post process effect blended with the main pass.
  93542. *
  93543. * This can be for instance use to generate glow or higlight effects on the scene.
  93544. *
  93545. * The effect layer class can not be used directly and is intented to inherited from to be
  93546. * customized per effects.
  93547. */
  93548. var EffectLayer = /** @class */ (function () {
  93549. /**
  93550. * Instantiates a new effect Layer and references it in the scene.
  93551. * @param name The name of the layer
  93552. * @param scene The scene to use the layer in
  93553. */
  93554. function EffectLayer(
  93555. /** The Friendly of the effect in the scene */
  93556. name, scene) {
  93557. this._vertexBuffers = {};
  93558. this._maxSize = 0;
  93559. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93560. this._shouldRender = true;
  93561. this._postProcesses = [];
  93562. this._textures = [];
  93563. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93564. /**
  93565. * The clear color of the texture used to generate the glow map.
  93566. */
  93567. this.neutralColor = new BABYLON.Color4();
  93568. /**
  93569. * Specifies wether the highlight layer is enabled or not.
  93570. */
  93571. this.isEnabled = true;
  93572. /**
  93573. * An event triggered when the effect layer has been disposed.
  93574. */
  93575. this.onDisposeObservable = new BABYLON.Observable();
  93576. /**
  93577. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93578. */
  93579. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93580. /**
  93581. * An event triggered when the generated texture is being merged in the scene.
  93582. */
  93583. this.onBeforeComposeObservable = new BABYLON.Observable();
  93584. /**
  93585. * An event triggered when the generated texture has been merged in the scene.
  93586. */
  93587. this.onAfterComposeObservable = new BABYLON.Observable();
  93588. /**
  93589. * An event triggered when the efffect layer changes its size.
  93590. */
  93591. this.onSizeChangedObservable = new BABYLON.Observable();
  93592. this.name = name;
  93593. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93594. this._engine = scene.getEngine();
  93595. this._maxSize = this._engine.getCaps().maxTextureSize;
  93596. this._scene.effectLayers.push(this);
  93597. // Generate Buffers
  93598. this._generateIndexBuffer();
  93599. this._genrateVertexBuffer();
  93600. }
  93601. Object.defineProperty(EffectLayer.prototype, "camera", {
  93602. /**
  93603. * Gets the camera attached to the layer.
  93604. */
  93605. get: function () {
  93606. return this._effectLayerOptions.camera;
  93607. },
  93608. enumerable: true,
  93609. configurable: true
  93610. });
  93611. /**
  93612. * Initializes the effect layer with the required options.
  93613. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  93614. */
  93615. EffectLayer.prototype._init = function (options) {
  93616. // Adapt options
  93617. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93618. this._setMainTextureSize();
  93619. this._createMainTexture();
  93620. this._createTextureAndPostProcesses();
  93621. this._mergeEffect = this._createMergeEffect();
  93622. };
  93623. /**
  93624. * Generates the index buffer of the full screen quad blending to the main canvas.
  93625. */
  93626. EffectLayer.prototype._generateIndexBuffer = function () {
  93627. // Indices
  93628. var indices = [];
  93629. indices.push(0);
  93630. indices.push(1);
  93631. indices.push(2);
  93632. indices.push(0);
  93633. indices.push(2);
  93634. indices.push(3);
  93635. this._indexBuffer = this._engine.createIndexBuffer(indices);
  93636. };
  93637. /**
  93638. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  93639. */
  93640. EffectLayer.prototype._genrateVertexBuffer = function () {
  93641. // VBO
  93642. var vertices = [];
  93643. vertices.push(1, 1);
  93644. vertices.push(-1, 1);
  93645. vertices.push(-1, -1);
  93646. vertices.push(1, -1);
  93647. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93648. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93649. };
  93650. /**
  93651. * Sets the main texture desired size which is the closest power of two
  93652. * of the engine canvas size.
  93653. */
  93654. EffectLayer.prototype._setMainTextureSize = function () {
  93655. if (this._effectLayerOptions.mainTextureFixedSize) {
  93656. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  93657. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  93658. }
  93659. else {
  93660. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  93661. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  93662. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  93663. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  93664. }
  93665. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  93666. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  93667. };
  93668. /**
  93669. * Creates the main texture for the effect layer.
  93670. */
  93671. EffectLayer.prototype._createMainTexture = function () {
  93672. var _this = this;
  93673. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  93674. width: this._mainTextureDesiredSize.width,
  93675. height: this._mainTextureDesiredSize.height
  93676. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93677. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  93678. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93679. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93680. this._mainTexture.anisotropicFilteringLevel = 1;
  93681. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93682. this._mainTexture.renderParticles = false;
  93683. this._mainTexture.renderList = null;
  93684. this._mainTexture.ignoreCameraViewport = true;
  93685. // Custom render function
  93686. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  93687. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  93688. var index;
  93689. var engine = _this._scene.getEngine();
  93690. if (depthOnlySubMeshes.length) {
  93691. engine.setColorWrite(false);
  93692. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  93693. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  93694. }
  93695. engine.setColorWrite(true);
  93696. }
  93697. for (index = 0; index < opaqueSubMeshes.length; index++) {
  93698. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  93699. }
  93700. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  93701. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  93702. }
  93703. for (index = 0; index < transparentSubMeshes.length; index++) {
  93704. _this._renderSubMesh(transparentSubMeshes.data[index]);
  93705. }
  93706. };
  93707. this._mainTexture.onClearObservable.add(function (engine) {
  93708. engine.clear(_this.neutralColor, true, true, true);
  93709. });
  93710. };
  93711. /**
  93712. * Checks for the readiness of the element composing the layer.
  93713. * @param subMesh the mesh to check for
  93714. * @param useInstances specify wether or not to use instances to render the mesh
  93715. * @param emissiveTexture the associated emissive texture used to generate the glow
  93716. * @return true if ready otherwise, false
  93717. */
  93718. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  93719. var material = subMesh.getMaterial();
  93720. if (!material) {
  93721. return false;
  93722. }
  93723. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  93724. return false;
  93725. }
  93726. var defines = [];
  93727. var attribs = [BABYLON.VertexBuffer.PositionKind];
  93728. var mesh = subMesh.getMesh();
  93729. var uv1 = false;
  93730. var uv2 = false;
  93731. // Alpha test
  93732. if (material && material.needAlphaTesting()) {
  93733. var alphaTexture = material.getAlphaTestTexture();
  93734. if (alphaTexture) {
  93735. defines.push("#define ALPHATEST");
  93736. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93737. alphaTexture.coordinatesIndex === 1) {
  93738. defines.push("#define DIFFUSEUV2");
  93739. uv2 = true;
  93740. }
  93741. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93742. defines.push("#define DIFFUSEUV1");
  93743. uv1 = true;
  93744. }
  93745. }
  93746. }
  93747. // Emissive
  93748. if (emissiveTexture) {
  93749. defines.push("#define EMISSIVE");
  93750. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93751. emissiveTexture.coordinatesIndex === 1) {
  93752. defines.push("#define EMISSIVEUV2");
  93753. uv2 = true;
  93754. }
  93755. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93756. defines.push("#define EMISSIVEUV1");
  93757. uv1 = true;
  93758. }
  93759. }
  93760. if (uv1) {
  93761. attribs.push(BABYLON.VertexBuffer.UVKind);
  93762. defines.push("#define UV1");
  93763. }
  93764. if (uv2) {
  93765. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93766. defines.push("#define UV2");
  93767. }
  93768. // Bones
  93769. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93770. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93771. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93772. if (mesh.numBoneInfluencers > 4) {
  93773. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93774. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93775. }
  93776. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93777. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  93778. }
  93779. else {
  93780. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93781. }
  93782. // Morph targets
  93783. var manager = mesh.morphTargetManager;
  93784. var morphInfluencers = 0;
  93785. if (manager) {
  93786. if (manager.numInfluencers > 0) {
  93787. defines.push("#define MORPHTARGETS");
  93788. morphInfluencers = manager.numInfluencers;
  93789. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  93790. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  93791. }
  93792. }
  93793. // Instances
  93794. if (useInstances) {
  93795. defines.push("#define INSTANCES");
  93796. attribs.push("world0");
  93797. attribs.push("world1");
  93798. attribs.push("world2");
  93799. attribs.push("world3");
  93800. }
  93801. // Get correct effect
  93802. var join = defines.join("\n");
  93803. if (this._cachedDefines !== join) {
  93804. this._cachedDefines = join;
  93805. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  93806. }
  93807. return this._effectLayerMapGenerationEffect.isReady();
  93808. };
  93809. /**
  93810. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  93811. */
  93812. EffectLayer.prototype.render = function () {
  93813. var currentEffect = this._mergeEffect;
  93814. // Check
  93815. if (!currentEffect.isReady())
  93816. return;
  93817. for (var i = 0; i < this._postProcesses.length; i++) {
  93818. if (!this._postProcesses[i].isReady()) {
  93819. return;
  93820. }
  93821. }
  93822. var engine = this._scene.getEngine();
  93823. this.onBeforeComposeObservable.notifyObservers(this);
  93824. // Render
  93825. engine.enableEffect(currentEffect);
  93826. engine.setState(false);
  93827. // VBOs
  93828. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93829. // Cache
  93830. var previousAlphaMode = engine.getAlphaMode();
  93831. // Go Blend.
  93832. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  93833. // Blends the map on the main canvas.
  93834. this._internalRender(currentEffect);
  93835. // Restore Alpha
  93836. engine.setAlphaMode(previousAlphaMode);
  93837. this.onAfterComposeObservable.notifyObservers(this);
  93838. // Handle size changes.
  93839. var size = this._mainTexture.getSize();
  93840. this._setMainTextureSize();
  93841. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  93842. // Recreate RTT and post processes on size change.
  93843. this.onSizeChangedObservable.notifyObservers(this);
  93844. this._disposeTextureAndPostProcesses();
  93845. this._createMainTexture();
  93846. this._createTextureAndPostProcesses();
  93847. }
  93848. };
  93849. /**
  93850. * Determine if a given mesh will be used in the current effect.
  93851. * @param mesh mesh to test
  93852. * @returns true if the mesh will be used
  93853. */
  93854. EffectLayer.prototype.hasMesh = function (mesh) {
  93855. return true;
  93856. };
  93857. /**
  93858. * Returns true if the layer contains information to display, otherwise false.
  93859. * @returns true if the glow layer should be rendered
  93860. */
  93861. EffectLayer.prototype.shouldRender = function () {
  93862. return this.isEnabled && this._shouldRender;
  93863. };
  93864. /**
  93865. * Returns true if the mesh should render, otherwise false.
  93866. * @param mesh The mesh to render
  93867. * @returns true if it should render otherwise false
  93868. */
  93869. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  93870. return true;
  93871. };
  93872. /**
  93873. * Returns true if the mesh should render, otherwise false.
  93874. * @param mesh The mesh to render
  93875. * @returns true if it should render otherwise false
  93876. */
  93877. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  93878. return true;
  93879. };
  93880. /**
  93881. * Renders the submesh passed in parameter to the generation map.
  93882. */
  93883. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  93884. var _this = this;
  93885. if (!this.shouldRender()) {
  93886. return;
  93887. }
  93888. var material = subMesh.getMaterial();
  93889. var mesh = subMesh.getRenderingMesh();
  93890. var scene = this._scene;
  93891. var engine = scene.getEngine();
  93892. if (!material) {
  93893. return;
  93894. }
  93895. // Do not block in blend mode.
  93896. if (material.needAlphaBlendingForMesh(mesh)) {
  93897. return;
  93898. }
  93899. // Culling
  93900. engine.setState(material.backFaceCulling);
  93901. // Managing instances
  93902. var batch = mesh._getInstancesRenderList(subMesh._id);
  93903. if (batch.mustReturn) {
  93904. return;
  93905. }
  93906. // Early Exit per mesh
  93907. if (!this._shouldRenderMesh(mesh)) {
  93908. return;
  93909. }
  93910. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93911. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  93912. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  93913. engine.enableEffect(this._effectLayerMapGenerationEffect);
  93914. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  93915. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  93916. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  93917. // Alpha test
  93918. if (material && material.needAlphaTesting()) {
  93919. var alphaTexture = material.getAlphaTestTexture();
  93920. if (alphaTexture) {
  93921. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  93922. var textureMatrix = alphaTexture.getTextureMatrix();
  93923. if (textureMatrix) {
  93924. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  93925. }
  93926. }
  93927. }
  93928. // Glow emissive only
  93929. if (this._emissiveTextureAndColor.texture) {
  93930. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  93931. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  93932. }
  93933. // Bones
  93934. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93935. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93936. }
  93937. // Morph targets
  93938. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  93939. // Draw
  93940. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  93941. }
  93942. else {
  93943. // Need to reset refresh rate of the shadowMap
  93944. this._mainTexture.resetRefreshCounter();
  93945. }
  93946. };
  93947. /**
  93948. * Rebuild the required buffers.
  93949. * @hidden Internal use only.
  93950. */
  93951. EffectLayer.prototype._rebuild = function () {
  93952. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93953. if (vb) {
  93954. vb._rebuild();
  93955. }
  93956. this._generateIndexBuffer();
  93957. };
  93958. /**
  93959. * Dispose only the render target textures and post process.
  93960. */
  93961. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  93962. this._mainTexture.dispose();
  93963. for (var i = 0; i < this._postProcesses.length; i++) {
  93964. if (this._postProcesses[i]) {
  93965. this._postProcesses[i].dispose();
  93966. }
  93967. }
  93968. this._postProcesses = [];
  93969. for (var i = 0; i < this._textures.length; i++) {
  93970. if (this._textures[i]) {
  93971. this._textures[i].dispose();
  93972. }
  93973. }
  93974. this._textures = [];
  93975. };
  93976. /**
  93977. * Dispose the highlight layer and free resources.
  93978. */
  93979. EffectLayer.prototype.dispose = function () {
  93980. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93981. if (vertexBuffer) {
  93982. vertexBuffer.dispose();
  93983. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93984. }
  93985. if (this._indexBuffer) {
  93986. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93987. this._indexBuffer = null;
  93988. }
  93989. // Clean textures and post processes
  93990. this._disposeTextureAndPostProcesses();
  93991. // Remove from scene
  93992. var index = this._scene.effectLayers.indexOf(this, 0);
  93993. if (index > -1) {
  93994. this._scene.effectLayers.splice(index, 1);
  93995. }
  93996. // Callback
  93997. this.onDisposeObservable.notifyObservers(this);
  93998. this.onDisposeObservable.clear();
  93999. this.onBeforeRenderMainTextureObservable.clear();
  94000. this.onBeforeComposeObservable.clear();
  94001. this.onAfterComposeObservable.clear();
  94002. this.onSizeChangedObservable.clear();
  94003. };
  94004. /**
  94005. * Gets the class name of the effect layer
  94006. * @returns the string with the class name of the effect layer
  94007. */
  94008. EffectLayer.prototype.getClassName = function () {
  94009. return "EffectLayer";
  94010. };
  94011. /**
  94012. * Creates an effect layer from parsed effect layer data
  94013. * @param parsedEffectLayer defines effect layer data
  94014. * @param scene defines the current scene
  94015. * @param rootUrl defines the root URL containing the effect layer information
  94016. * @returns a parsed effect Layer
  94017. */
  94018. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  94019. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  94020. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  94021. };
  94022. __decorate([
  94023. BABYLON.serialize()
  94024. ], EffectLayer.prototype, "name", void 0);
  94025. __decorate([
  94026. BABYLON.serializeAsColor4()
  94027. ], EffectLayer.prototype, "neutralColor", void 0);
  94028. __decorate([
  94029. BABYLON.serialize()
  94030. ], EffectLayer.prototype, "isEnabled", void 0);
  94031. __decorate([
  94032. BABYLON.serializeAsCameraReference()
  94033. ], EffectLayer.prototype, "camera", null);
  94034. return EffectLayer;
  94035. }());
  94036. BABYLON.EffectLayer = EffectLayer;
  94037. })(BABYLON || (BABYLON = {}));
  94038. //# sourceMappingURL=babylon.effectLayer.js.map
  94039. var BABYLON;
  94040. (function (BABYLON) {
  94041. /**
  94042. * Special Glow Blur post process only blurring the alpha channel
  94043. * It enforces keeping the most luminous color in the color channel.
  94044. */
  94045. var GlowBlurPostProcess = /** @class */ (function (_super) {
  94046. __extends(GlowBlurPostProcess, _super);
  94047. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  94048. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  94049. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  94050. _this.direction = direction;
  94051. _this.kernel = kernel;
  94052. _this.onApplyObservable.add(function (effect) {
  94053. effect.setFloat2("screenSize", _this.width, _this.height);
  94054. effect.setVector2("direction", _this.direction);
  94055. effect.setFloat("blurWidth", _this.kernel);
  94056. });
  94057. return _this;
  94058. }
  94059. return GlowBlurPostProcess;
  94060. }(BABYLON.PostProcess));
  94061. /**
  94062. * The highlight layer Helps adding a glow effect around a mesh.
  94063. *
  94064. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94065. * glowy meshes to your scene.
  94066. *
  94067. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  94068. */
  94069. var HighlightLayer = /** @class */ (function (_super) {
  94070. __extends(HighlightLayer, _super);
  94071. /**
  94072. * Instantiates a new highlight Layer and references it to the scene..
  94073. * @param name The name of the layer
  94074. * @param scene The scene to use the layer in
  94075. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  94076. */
  94077. function HighlightLayer(name, scene, options) {
  94078. var _this = _super.call(this, name, scene) || this;
  94079. _this.name = name;
  94080. /**
  94081. * Specifies whether or not the inner glow is ACTIVE in the layer.
  94082. */
  94083. _this.innerGlow = true;
  94084. /**
  94085. * Specifies whether or not the outer glow is ACTIVE in the layer.
  94086. */
  94087. _this.outerGlow = true;
  94088. /**
  94089. * An event triggered when the highlight layer is being blurred.
  94090. */
  94091. _this.onBeforeBlurObservable = new BABYLON.Observable();
  94092. /**
  94093. * An event triggered when the highlight layer has been blurred.
  94094. */
  94095. _this.onAfterBlurObservable = new BABYLON.Observable();
  94096. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  94097. _this._meshes = {};
  94098. _this._excludedMeshes = {};
  94099. _this.neutralColor = HighlightLayer.NeutralColor;
  94100. // Warn on stencil
  94101. if (!_this._engine.isStencilEnable) {
  94102. 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 }");
  94103. }
  94104. // Adapt options
  94105. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94106. // Initialize the layer
  94107. _this._init({
  94108. alphaBlendingMode: _this._options.alphaBlendingMode,
  94109. camera: _this._options.camera,
  94110. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94111. mainTextureRatio: _this._options.mainTextureRatio
  94112. });
  94113. // Do not render as long as no meshes have been added
  94114. _this._shouldRender = false;
  94115. return _this;
  94116. }
  94117. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94118. /**
  94119. * Gets the horizontal size of the blur.
  94120. */
  94121. get: function () {
  94122. return this._horizontalBlurPostprocess.kernel;
  94123. },
  94124. /**
  94125. * Specifies the horizontal size of the blur.
  94126. */
  94127. set: function (value) {
  94128. this._horizontalBlurPostprocess.kernel = value;
  94129. },
  94130. enumerable: true,
  94131. configurable: true
  94132. });
  94133. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94134. /**
  94135. * Gets the vertical size of the blur.
  94136. */
  94137. get: function () {
  94138. return this._verticalBlurPostprocess.kernel;
  94139. },
  94140. /**
  94141. * Specifies the vertical size of the blur.
  94142. */
  94143. set: function (value) {
  94144. this._verticalBlurPostprocess.kernel = value;
  94145. },
  94146. enumerable: true,
  94147. configurable: true
  94148. });
  94149. /**
  94150. * Get the effect name of the layer.
  94151. * @return The effect name
  94152. */
  94153. HighlightLayer.prototype.getEffectName = function () {
  94154. return HighlightLayer.EffectName;
  94155. };
  94156. /**
  94157. * Create the merge effect. This is the shader use to blit the information back
  94158. * to the main canvas at the end of the scene rendering.
  94159. */
  94160. HighlightLayer.prototype._createMergeEffect = function () {
  94161. // Effect
  94162. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94163. };
  94164. /**
  94165. * Creates the render target textures and post processes used in the highlight layer.
  94166. */
  94167. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94168. var _this = this;
  94169. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94170. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94171. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94172. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94173. var textureType = 0;
  94174. if (this._engine.getCaps().textureHalfFloatRender) {
  94175. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94176. }
  94177. else {
  94178. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94179. }
  94180. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94181. width: blurTextureWidth,
  94182. height: blurTextureHeight
  94183. }, this._scene, false, true, textureType);
  94184. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94185. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94186. this._blurTexture.anisotropicFilteringLevel = 16;
  94187. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94188. this._blurTexture.renderParticles = false;
  94189. this._blurTexture.ignoreCameraViewport = true;
  94190. this._textures = [this._blurTexture];
  94191. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94192. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94193. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94194. effect.setTexture("textureSampler", _this._mainTexture);
  94195. });
  94196. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94197. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94198. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94199. });
  94200. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94201. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94202. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94203. });
  94204. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94205. }
  94206. else {
  94207. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94208. width: blurTextureWidth,
  94209. height: blurTextureHeight
  94210. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94211. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94212. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94213. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94214. effect.setTexture("textureSampler", _this._mainTexture);
  94215. });
  94216. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94217. width: blurTextureWidth,
  94218. height: blurTextureHeight
  94219. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94220. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94221. }
  94222. this._mainTexture.onAfterUnbindObservable.add(function () {
  94223. _this.onBeforeBlurObservable.notifyObservers(_this);
  94224. var internalTexture = _this._blurTexture.getInternalTexture();
  94225. if (internalTexture) {
  94226. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94227. }
  94228. _this.onAfterBlurObservable.notifyObservers(_this);
  94229. });
  94230. // Prevent autoClear.
  94231. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94232. };
  94233. /**
  94234. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94235. */
  94236. HighlightLayer.prototype.needStencil = function () {
  94237. return true;
  94238. };
  94239. /**
  94240. * Checks for the readiness of the element composing the layer.
  94241. * @param subMesh the mesh to check for
  94242. * @param useInstances specify wether or not to use instances to render the mesh
  94243. * @param emissiveTexture the associated emissive texture used to generate the glow
  94244. * @return true if ready otherwise, false
  94245. */
  94246. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94247. var material = subMesh.getMaterial();
  94248. var mesh = subMesh.getRenderingMesh();
  94249. if (!material || !mesh || !this._meshes) {
  94250. return false;
  94251. }
  94252. var emissiveTexture = null;
  94253. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94254. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94255. emissiveTexture = material.emissiveTexture;
  94256. }
  94257. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94258. };
  94259. /**
  94260. * Implementation specific of rendering the generating effect on the main canvas.
  94261. * @param effect The effect used to render through
  94262. */
  94263. HighlightLayer.prototype._internalRender = function (effect) {
  94264. // Texture
  94265. effect.setTexture("textureSampler", this._blurTexture);
  94266. // Cache
  94267. var engine = this._engine;
  94268. var previousStencilBuffer = engine.getStencilBuffer();
  94269. var previousStencilFunction = engine.getStencilFunction();
  94270. var previousStencilMask = engine.getStencilMask();
  94271. var previousStencilOperationPass = engine.getStencilOperationPass();
  94272. var previousStencilOperationFail = engine.getStencilOperationFail();
  94273. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94274. var previousStencilReference = engine.getStencilFunctionReference();
  94275. // Stencil operations
  94276. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94277. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94278. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94279. // Draw order
  94280. engine.setStencilMask(0x00);
  94281. engine.setStencilBuffer(true);
  94282. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94283. // 2 passes inner outer
  94284. if (this.outerGlow) {
  94285. effect.setFloat("offset", 0);
  94286. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94287. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94288. }
  94289. if (this.innerGlow) {
  94290. effect.setFloat("offset", 1);
  94291. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94292. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94293. }
  94294. // Restore Cache
  94295. engine.setStencilFunction(previousStencilFunction);
  94296. engine.setStencilMask(previousStencilMask);
  94297. engine.setStencilBuffer(previousStencilBuffer);
  94298. engine.setStencilOperationPass(previousStencilOperationPass);
  94299. engine.setStencilOperationFail(previousStencilOperationFail);
  94300. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94301. engine.setStencilFunctionReference(previousStencilReference);
  94302. };
  94303. /**
  94304. * Returns true if the layer contains information to display, otherwise false.
  94305. */
  94306. HighlightLayer.prototype.shouldRender = function () {
  94307. if (_super.prototype.shouldRender.call(this)) {
  94308. return this._meshes ? true : false;
  94309. }
  94310. return false;
  94311. };
  94312. /**
  94313. * Returns true if the mesh should render, otherwise false.
  94314. * @param mesh The mesh to render
  94315. * @returns true if it should render otherwise false
  94316. */
  94317. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94318. // Excluded Mesh
  94319. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94320. return false;
  94321. }
  94322. ;
  94323. return true;
  94324. };
  94325. /**
  94326. * Sets the required values for both the emissive texture and and the main color.
  94327. */
  94328. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94329. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94330. if (highlightLayerMesh) {
  94331. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94332. }
  94333. else {
  94334. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94335. }
  94336. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94337. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94338. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94339. }
  94340. else {
  94341. this._emissiveTextureAndColor.texture = null;
  94342. }
  94343. };
  94344. /**
  94345. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94346. * @param mesh The mesh to exclude from the highlight layer
  94347. */
  94348. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94349. if (!this._excludedMeshes) {
  94350. return;
  94351. }
  94352. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94353. if (!meshExcluded) {
  94354. this._excludedMeshes[mesh.uniqueId] = {
  94355. mesh: mesh,
  94356. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94357. mesh.getEngine().setStencilBuffer(false);
  94358. }),
  94359. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94360. mesh.getEngine().setStencilBuffer(true);
  94361. }),
  94362. };
  94363. }
  94364. };
  94365. /**
  94366. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94367. * @param mesh The mesh to highlight
  94368. */
  94369. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94370. if (!this._excludedMeshes) {
  94371. return;
  94372. }
  94373. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94374. if (meshExcluded) {
  94375. if (meshExcluded.beforeRender) {
  94376. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94377. }
  94378. if (meshExcluded.afterRender) {
  94379. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94380. }
  94381. }
  94382. this._excludedMeshes[mesh.uniqueId] = null;
  94383. };
  94384. /**
  94385. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94386. * @param mesh mesh to test
  94387. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94388. */
  94389. HighlightLayer.prototype.hasMesh = function (mesh) {
  94390. if (!this._meshes) {
  94391. return false;
  94392. }
  94393. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94394. };
  94395. /**
  94396. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94397. * @param mesh The mesh to highlight
  94398. * @param color The color of the highlight
  94399. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94400. */
  94401. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94402. var _this = this;
  94403. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94404. if (!this._meshes) {
  94405. return;
  94406. }
  94407. var meshHighlight = this._meshes[mesh.uniqueId];
  94408. if (meshHighlight) {
  94409. meshHighlight.color = color;
  94410. }
  94411. else {
  94412. this._meshes[mesh.uniqueId] = {
  94413. mesh: mesh,
  94414. color: color,
  94415. // Lambda required for capture due to Observable this context
  94416. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94417. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94418. _this._defaultStencilReference(mesh);
  94419. }
  94420. else {
  94421. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94422. }
  94423. }),
  94424. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94425. glowEmissiveOnly: glowEmissiveOnly
  94426. };
  94427. }
  94428. this._shouldRender = true;
  94429. };
  94430. /**
  94431. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94432. * @param mesh The mesh to highlight
  94433. */
  94434. HighlightLayer.prototype.removeMesh = function (mesh) {
  94435. if (!this._meshes) {
  94436. return;
  94437. }
  94438. var meshHighlight = this._meshes[mesh.uniqueId];
  94439. if (meshHighlight) {
  94440. if (meshHighlight.observerHighlight) {
  94441. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94442. }
  94443. if (meshHighlight.observerDefault) {
  94444. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94445. }
  94446. delete this._meshes[mesh.uniqueId];
  94447. }
  94448. this._shouldRender = false;
  94449. for (var meshHighlightToCheck in this._meshes) {
  94450. if (this._meshes[meshHighlightToCheck]) {
  94451. this._shouldRender = true;
  94452. break;
  94453. }
  94454. }
  94455. };
  94456. /**
  94457. * Force the stencil to the normal expected value for none glowing parts
  94458. */
  94459. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94460. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94461. };
  94462. /**
  94463. * Free any resources and references associated to a mesh.
  94464. * Internal use
  94465. * @param mesh The mesh to free.
  94466. */
  94467. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94468. this.removeMesh(mesh);
  94469. this.removeExcludedMesh(mesh);
  94470. };
  94471. /**
  94472. * Dispose the highlight layer and free resources.
  94473. */
  94474. HighlightLayer.prototype.dispose = function () {
  94475. if (this._meshes) {
  94476. // Clean mesh references
  94477. for (var id in this._meshes) {
  94478. var meshHighlight = this._meshes[id];
  94479. if (meshHighlight && meshHighlight.mesh) {
  94480. if (meshHighlight.observerHighlight) {
  94481. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94482. }
  94483. if (meshHighlight.observerDefault) {
  94484. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94485. }
  94486. }
  94487. }
  94488. this._meshes = null;
  94489. }
  94490. if (this._excludedMeshes) {
  94491. for (var id in this._excludedMeshes) {
  94492. var meshHighlight = this._excludedMeshes[id];
  94493. if (meshHighlight) {
  94494. if (meshHighlight.beforeRender) {
  94495. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94496. }
  94497. if (meshHighlight.afterRender) {
  94498. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94499. }
  94500. }
  94501. }
  94502. this._excludedMeshes = null;
  94503. }
  94504. _super.prototype.dispose.call(this);
  94505. };
  94506. /**
  94507. * Gets the class name of the effect layer
  94508. * @returns the string with the class name of the effect layer
  94509. */
  94510. HighlightLayer.prototype.getClassName = function () {
  94511. return "HighlightLayer";
  94512. };
  94513. /**
  94514. * Serializes this Highlight layer
  94515. * @returns a serialized Highlight layer object
  94516. */
  94517. HighlightLayer.prototype.serialize = function () {
  94518. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94519. serializationObject.customType = "BABYLON.HighlightLayer";
  94520. // Highlighted meshes
  94521. serializationObject.meshes = [];
  94522. if (this._meshes) {
  94523. for (var m in this._meshes) {
  94524. var mesh = this._meshes[m];
  94525. if (mesh) {
  94526. serializationObject.meshes.push({
  94527. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94528. color: mesh.color.asArray(),
  94529. meshId: mesh.mesh.id
  94530. });
  94531. }
  94532. }
  94533. }
  94534. // Excluded meshes
  94535. serializationObject.excludedMeshes = [];
  94536. if (this._excludedMeshes) {
  94537. for (var e in this._excludedMeshes) {
  94538. var excludedMesh = this._excludedMeshes[e];
  94539. if (excludedMesh) {
  94540. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94541. }
  94542. }
  94543. }
  94544. return serializationObject;
  94545. };
  94546. /**
  94547. * Creates a Highlight layer from parsed Highlight layer data
  94548. * @param parsedHightlightLayer defines the Highlight layer data
  94549. * @param scene defines the current scene
  94550. * @param rootUrl defines the root URL containing the Highlight layer information
  94551. * @returns a parsed Highlight layer
  94552. */
  94553. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94554. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94555. var index;
  94556. // Excluded meshes
  94557. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94558. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94559. if (mesh) {
  94560. hl.addExcludedMesh(mesh);
  94561. }
  94562. }
  94563. // Included meshes
  94564. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94565. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94566. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94567. if (mesh) {
  94568. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94569. }
  94570. }
  94571. return hl;
  94572. };
  94573. /**
  94574. * Effect Name of the highlight layer.
  94575. */
  94576. HighlightLayer.EffectName = "HighlightLayer";
  94577. /**
  94578. * The neutral color used during the preparation of the glow effect.
  94579. * This is black by default as the blend operation is a blend operation.
  94580. */
  94581. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94582. /**
  94583. * Stencil value used for glowing meshes.
  94584. */
  94585. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94586. /**
  94587. * Stencil value used for the other meshes in the scene.
  94588. */
  94589. HighlightLayer.NormalMeshStencilReference = 0x01;
  94590. __decorate([
  94591. BABYLON.serialize()
  94592. ], HighlightLayer.prototype, "innerGlow", void 0);
  94593. __decorate([
  94594. BABYLON.serialize()
  94595. ], HighlightLayer.prototype, "outerGlow", void 0);
  94596. __decorate([
  94597. BABYLON.serialize()
  94598. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  94599. __decorate([
  94600. BABYLON.serialize()
  94601. ], HighlightLayer.prototype, "blurVerticalSize", null);
  94602. __decorate([
  94603. BABYLON.serialize("options")
  94604. ], HighlightLayer.prototype, "_options", void 0);
  94605. return HighlightLayer;
  94606. }(BABYLON.EffectLayer));
  94607. BABYLON.HighlightLayer = HighlightLayer;
  94608. })(BABYLON || (BABYLON = {}));
  94609. //# sourceMappingURL=babylon.highlightLayer.js.map
  94610. var BABYLON;
  94611. (function (BABYLON) {
  94612. /**
  94613. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  94614. *
  94615. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94616. * glowy meshes to your scene.
  94617. *
  94618. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  94619. */
  94620. var GlowLayer = /** @class */ (function (_super) {
  94621. __extends(GlowLayer, _super);
  94622. /**
  94623. * Instantiates a new glow Layer and references it to the scene.
  94624. * @param name The name of the layer
  94625. * @param scene The scene to use the layer in
  94626. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  94627. */
  94628. function GlowLayer(name, scene, options) {
  94629. var _this = _super.call(this, name, scene) || this;
  94630. _this._intensity = 1.0;
  94631. _this._includedOnlyMeshes = [];
  94632. _this._excludedMeshes = [];
  94633. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  94634. // Adapt options
  94635. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  94636. // Initialize the layer
  94637. _this._init({
  94638. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  94639. camera: _this._options.camera,
  94640. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94641. mainTextureRatio: _this._options.mainTextureRatio
  94642. });
  94643. return _this;
  94644. }
  94645. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  94646. /**
  94647. * Gets the kernel size of the blur.
  94648. */
  94649. get: function () {
  94650. return this._horizontalBlurPostprocess1.kernel;
  94651. },
  94652. /**
  94653. * Sets the kernel size of the blur.
  94654. */
  94655. set: function (value) {
  94656. this._horizontalBlurPostprocess1.kernel = value;
  94657. this._verticalBlurPostprocess1.kernel = value;
  94658. this._horizontalBlurPostprocess2.kernel = value;
  94659. this._verticalBlurPostprocess2.kernel = value;
  94660. },
  94661. enumerable: true,
  94662. configurable: true
  94663. });
  94664. Object.defineProperty(GlowLayer.prototype, "intensity", {
  94665. /**
  94666. * Gets the glow intensity.
  94667. */
  94668. get: function () {
  94669. return this._intensity;
  94670. },
  94671. /**
  94672. * Sets the glow intensity.
  94673. */
  94674. set: function (value) {
  94675. this._intensity = value;
  94676. },
  94677. enumerable: true,
  94678. configurable: true
  94679. });
  94680. /**
  94681. * Get the effect name of the layer.
  94682. * @return The effect name
  94683. */
  94684. GlowLayer.prototype.getEffectName = function () {
  94685. return GlowLayer.EffectName;
  94686. };
  94687. /**
  94688. * Create the merge effect. This is the shader use to blit the information back
  94689. * to the main canvas at the end of the scene rendering.
  94690. */
  94691. GlowLayer.prototype._createMergeEffect = function () {
  94692. // Effect
  94693. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  94694. };
  94695. /**
  94696. * Creates the render target textures and post processes used in the glow layer.
  94697. */
  94698. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  94699. var _this = this;
  94700. var blurTextureWidth = this._mainTextureDesiredSize.width;
  94701. var blurTextureHeight = this._mainTextureDesiredSize.height;
  94702. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94703. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94704. var textureType = 0;
  94705. if (this._engine.getCaps().textureHalfFloatRender) {
  94706. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94707. }
  94708. else {
  94709. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94710. }
  94711. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  94712. width: blurTextureWidth,
  94713. height: blurTextureHeight
  94714. }, this._scene, false, true, textureType);
  94715. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94716. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94717. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94718. this._blurTexture1.renderParticles = false;
  94719. this._blurTexture1.ignoreCameraViewport = true;
  94720. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  94721. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  94722. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  94723. width: blurTextureWidth2,
  94724. height: blurTextureHeight2
  94725. }, this._scene, false, true, textureType);
  94726. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94727. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94728. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94729. this._blurTexture2.renderParticles = false;
  94730. this._blurTexture2.ignoreCameraViewport = true;
  94731. this._textures = [this._blurTexture1, this._blurTexture2];
  94732. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94733. width: blurTextureWidth,
  94734. height: blurTextureHeight
  94735. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94736. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  94737. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  94738. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  94739. effect.setTexture("textureSampler", _this._mainTexture);
  94740. });
  94741. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94742. width: blurTextureWidth,
  94743. height: blurTextureHeight
  94744. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94745. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94746. width: blurTextureWidth2,
  94747. height: blurTextureHeight2
  94748. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94749. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  94750. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  94751. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  94752. effect.setTexture("textureSampler", _this._blurTexture1);
  94753. });
  94754. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94755. width: blurTextureWidth2,
  94756. height: blurTextureHeight2
  94757. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94758. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94759. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  94760. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94761. this._mainTexture.samples = this._options.mainTextureSamples;
  94762. this._mainTexture.onAfterUnbindObservable.add(function () {
  94763. var internalTexture = _this._blurTexture1.getInternalTexture();
  94764. if (internalTexture) {
  94765. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  94766. internalTexture = _this._blurTexture2.getInternalTexture();
  94767. if (internalTexture) {
  94768. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  94769. }
  94770. }
  94771. });
  94772. // Prevent autoClear.
  94773. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94774. };
  94775. /**
  94776. * Checks for the readiness of the element composing the layer.
  94777. * @param subMesh the mesh to check for
  94778. * @param useInstances specify wether or not to use instances to render the mesh
  94779. * @param emissiveTexture the associated emissive texture used to generate the glow
  94780. * @return true if ready otherwise, false
  94781. */
  94782. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  94783. var material = subMesh.getMaterial();
  94784. var mesh = subMesh.getRenderingMesh();
  94785. if (!material || !mesh) {
  94786. return false;
  94787. }
  94788. var emissiveTexture = material.emissiveTexture;
  94789. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94790. };
  94791. /**
  94792. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94793. */
  94794. GlowLayer.prototype.needStencil = function () {
  94795. return false;
  94796. };
  94797. /**
  94798. * Implementation specific of rendering the generating effect on the main canvas.
  94799. * @param effect The effect used to render through
  94800. */
  94801. GlowLayer.prototype._internalRender = function (effect) {
  94802. // Texture
  94803. effect.setTexture("textureSampler", this._blurTexture1);
  94804. effect.setTexture("textureSampler2", this._blurTexture2);
  94805. effect.setFloat("offset", this._intensity);
  94806. // Cache
  94807. var engine = this._engine;
  94808. var previousStencilBuffer = engine.getStencilBuffer();
  94809. // Draw order
  94810. engine.setStencilBuffer(false);
  94811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94812. // Draw order
  94813. engine.setStencilBuffer(previousStencilBuffer);
  94814. };
  94815. /**
  94816. * Sets the required values for both the emissive texture and and the main color.
  94817. */
  94818. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94819. var textureLevel = 1.0;
  94820. if (this.customEmissiveTextureSelector) {
  94821. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  94822. }
  94823. else {
  94824. if (material) {
  94825. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94826. if (this._emissiveTextureAndColor.texture) {
  94827. textureLevel = this._emissiveTextureAndColor.texture.level;
  94828. }
  94829. }
  94830. else {
  94831. this._emissiveTextureAndColor.texture = null;
  94832. }
  94833. }
  94834. if (this.customEmissiveColorSelector) {
  94835. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  94836. }
  94837. else {
  94838. if (material.emissiveColor) {
  94839. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  94840. }
  94841. else {
  94842. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94843. }
  94844. }
  94845. };
  94846. /**
  94847. * Returns true if the mesh should render, otherwise false.
  94848. * @param mesh The mesh to render
  94849. * @returns true if it should render otherwise false
  94850. */
  94851. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  94852. return this.hasMesh(mesh);
  94853. };
  94854. /**
  94855. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  94856. * @param mesh The mesh to exclude from the glow layer
  94857. */
  94858. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  94859. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  94860. this._excludedMeshes.push(mesh.uniqueId);
  94861. }
  94862. };
  94863. /**
  94864. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  94865. * @param mesh The mesh to remove
  94866. */
  94867. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  94868. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  94869. if (index !== -1) {
  94870. this._excludedMeshes.splice(index, 1);
  94871. }
  94872. };
  94873. /**
  94874. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  94875. * @param mesh The mesh to include in the glow layer
  94876. */
  94877. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  94878. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  94879. this._includedOnlyMeshes.push(mesh.uniqueId);
  94880. }
  94881. };
  94882. /**
  94883. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  94884. * @param mesh The mesh to remove
  94885. */
  94886. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  94887. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  94888. if (index !== -1) {
  94889. this._includedOnlyMeshes.splice(index, 1);
  94890. }
  94891. };
  94892. /**
  94893. * Determine if a given mesh will be used in the glow layer
  94894. * @param mesh The mesh to test
  94895. * @returns true if the mesh will be highlighted by the current glow layer
  94896. */
  94897. GlowLayer.prototype.hasMesh = function (mesh) {
  94898. // Included Mesh
  94899. if (this._includedOnlyMeshes.length) {
  94900. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  94901. }
  94902. ;
  94903. // Excluded Mesh
  94904. if (this._excludedMeshes.length) {
  94905. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  94906. }
  94907. ;
  94908. return true;
  94909. };
  94910. /**
  94911. * Free any resources and references associated to a mesh.
  94912. * Internal use
  94913. * @param mesh The mesh to free.
  94914. */
  94915. GlowLayer.prototype._disposeMesh = function (mesh) {
  94916. this.removeIncludedOnlyMesh(mesh);
  94917. this.removeExcludedMesh(mesh);
  94918. };
  94919. /**
  94920. * Gets the class name of the effect layer
  94921. * @returns the string with the class name of the effect layer
  94922. */
  94923. GlowLayer.prototype.getClassName = function () {
  94924. return "GlowLayer";
  94925. };
  94926. /**
  94927. * Serializes this glow layer
  94928. * @returns a serialized glow layer object
  94929. */
  94930. GlowLayer.prototype.serialize = function () {
  94931. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94932. serializationObject.customType = "BABYLON.GlowLayer";
  94933. var index;
  94934. // Included meshes
  94935. serializationObject.includedMeshes = [];
  94936. if (this._includedOnlyMeshes.length) {
  94937. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  94938. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  94939. if (mesh) {
  94940. serializationObject.includedMeshes.push(mesh.id);
  94941. }
  94942. }
  94943. }
  94944. // Excluded meshes
  94945. serializationObject.excludedMeshes = [];
  94946. if (this._excludedMeshes.length) {
  94947. for (index = 0; index < this._excludedMeshes.length; index++) {
  94948. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  94949. if (mesh) {
  94950. serializationObject.excludedMeshes.push(mesh.id);
  94951. }
  94952. }
  94953. }
  94954. return serializationObject;
  94955. };
  94956. /**
  94957. * Creates a Glow Layer from parsed glow layer data
  94958. * @param parsedGlowLayer defines glow layer data
  94959. * @param scene defines the current scene
  94960. * @param rootUrl defines the root URL containing the glow layer information
  94961. * @returns a parsed Glow Layer
  94962. */
  94963. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  94964. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  94965. var index;
  94966. // Excluded meshes
  94967. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  94968. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  94969. if (mesh) {
  94970. gl.addExcludedMesh(mesh);
  94971. }
  94972. }
  94973. // Included meshes
  94974. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  94975. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  94976. if (mesh) {
  94977. gl.addIncludedOnlyMesh(mesh);
  94978. }
  94979. }
  94980. return gl;
  94981. };
  94982. /**
  94983. * Effect Name of the layer.
  94984. */
  94985. GlowLayer.EffectName = "GlowLayer";
  94986. /**
  94987. * The default blur kernel size used for the glow.
  94988. */
  94989. GlowLayer.DefaultBlurKernelSize = 32;
  94990. /**
  94991. * The default texture size ratio used for the glow.
  94992. */
  94993. GlowLayer.DefaultTextureRatio = 0.5;
  94994. __decorate([
  94995. BABYLON.serialize()
  94996. ], GlowLayer.prototype, "blurKernelSize", null);
  94997. __decorate([
  94998. BABYLON.serialize()
  94999. ], GlowLayer.prototype, "intensity", null);
  95000. __decorate([
  95001. BABYLON.serialize("options")
  95002. ], GlowLayer.prototype, "_options", void 0);
  95003. return GlowLayer;
  95004. }(BABYLON.EffectLayer));
  95005. BABYLON.GlowLayer = GlowLayer;
  95006. })(BABYLON || (BABYLON = {}));
  95007. //# sourceMappingURL=babylon.glowLayer.js.map
  95008. var BABYLON;
  95009. (function (BABYLON) {
  95010. /**
  95011. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  95012. */
  95013. var AssetTaskState;
  95014. (function (AssetTaskState) {
  95015. /**
  95016. * Initialization
  95017. */
  95018. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  95019. /**
  95020. * Running
  95021. */
  95022. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  95023. /**
  95024. * Done
  95025. */
  95026. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  95027. /**
  95028. * Error
  95029. */
  95030. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  95031. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  95032. /**
  95033. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  95034. */
  95035. var AbstractAssetTask = /** @class */ (function () {
  95036. /**
  95037. * Creates a new {BABYLON.AssetsManager}
  95038. * @param name defines the name of the task
  95039. */
  95040. function AbstractAssetTask(
  95041. /**
  95042. * Task name
  95043. */ name) {
  95044. this.name = name;
  95045. this._isCompleted = false;
  95046. this._taskState = AssetTaskState.INIT;
  95047. }
  95048. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  95049. /**
  95050. * Get if the task is completed
  95051. */
  95052. get: function () {
  95053. return this._isCompleted;
  95054. },
  95055. enumerable: true,
  95056. configurable: true
  95057. });
  95058. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  95059. /**
  95060. * Gets the current state of the task
  95061. */
  95062. get: function () {
  95063. return this._taskState;
  95064. },
  95065. enumerable: true,
  95066. configurable: true
  95067. });
  95068. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  95069. /**
  95070. * Gets the current error object (if task is in error)
  95071. */
  95072. get: function () {
  95073. return this._errorObject;
  95074. },
  95075. enumerable: true,
  95076. configurable: true
  95077. });
  95078. /**
  95079. * Internal only
  95080. * @hidden
  95081. */
  95082. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  95083. if (this._errorObject) {
  95084. return;
  95085. }
  95086. this._errorObject = {
  95087. message: message,
  95088. exception: exception
  95089. };
  95090. };
  95091. /**
  95092. * Execute the current task
  95093. * @param scene defines the scene where you want your assets to be loaded
  95094. * @param onSuccess is a callback called when the task is successfully executed
  95095. * @param onError is a callback called if an error occurs
  95096. */
  95097. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95098. var _this = this;
  95099. this._taskState = AssetTaskState.RUNNING;
  95100. this.runTask(scene, function () {
  95101. _this.onDoneCallback(onSuccess, onError);
  95102. }, function (msg, exception) {
  95103. _this.onErrorCallback(onError, msg, exception);
  95104. });
  95105. };
  95106. /**
  95107. * Execute the current task
  95108. * @param scene defines the scene where you want your assets to be loaded
  95109. * @param onSuccess is a callback called when the task is successfully executed
  95110. * @param onError is a callback called if an error occurs
  95111. */
  95112. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95113. throw new Error("runTask is not implemented");
  95114. };
  95115. /**
  95116. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95117. * This can be used with failed tasks that have the reason for failure fixed.
  95118. */
  95119. AbstractAssetTask.prototype.reset = function () {
  95120. this._taskState = AssetTaskState.INIT;
  95121. };
  95122. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95123. this._taskState = AssetTaskState.ERROR;
  95124. this._errorObject = {
  95125. message: message,
  95126. exception: exception
  95127. };
  95128. if (this.onError) {
  95129. this.onError(this, message, exception);
  95130. }
  95131. onError();
  95132. };
  95133. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95134. try {
  95135. this._taskState = AssetTaskState.DONE;
  95136. this._isCompleted = true;
  95137. if (this.onSuccess) {
  95138. this.onSuccess(this);
  95139. }
  95140. onSuccess();
  95141. }
  95142. catch (e) {
  95143. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95144. }
  95145. };
  95146. return AbstractAssetTask;
  95147. }());
  95148. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95149. /**
  95150. * Class used to share progress information about assets loading
  95151. */
  95152. var AssetsProgressEvent = /** @class */ (function () {
  95153. /**
  95154. * Creates a {BABYLON.AssetsProgressEvent}
  95155. * @param remainingCount defines the number of remaining tasks to process
  95156. * @param totalCount defines the total number of tasks
  95157. * @param task defines the task that was just processed
  95158. */
  95159. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95160. this.remainingCount = remainingCount;
  95161. this.totalCount = totalCount;
  95162. this.task = task;
  95163. }
  95164. return AssetsProgressEvent;
  95165. }());
  95166. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95167. /**
  95168. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95169. */
  95170. var MeshAssetTask = /** @class */ (function (_super) {
  95171. __extends(MeshAssetTask, _super);
  95172. /**
  95173. * Creates a new {BABYLON.MeshAssetTask}
  95174. * @param name defines the name of the task
  95175. * @param meshesNames defines the list of mesh's names you want to load
  95176. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95177. * @param sceneFilename defines the filename of the scene to load from
  95178. */
  95179. function MeshAssetTask(
  95180. /**
  95181. * Defines the name of the task
  95182. */
  95183. name,
  95184. /**
  95185. * Defines the list of mesh's names you want to load
  95186. */
  95187. meshesNames,
  95188. /**
  95189. * Defines the root url to use as a base to load your meshes and associated resources
  95190. */
  95191. rootUrl,
  95192. /**
  95193. * Defines the filename of the scene to load from
  95194. */
  95195. sceneFilename) {
  95196. var _this = _super.call(this, name) || this;
  95197. _this.name = name;
  95198. _this.meshesNames = meshesNames;
  95199. _this.rootUrl = rootUrl;
  95200. _this.sceneFilename = sceneFilename;
  95201. return _this;
  95202. }
  95203. /**
  95204. * Execute the current task
  95205. * @param scene defines the scene where you want your assets to be loaded
  95206. * @param onSuccess is a callback called when the task is successfully executed
  95207. * @param onError is a callback called if an error occurs
  95208. */
  95209. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95210. var _this = this;
  95211. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95212. _this.loadedMeshes = meshes;
  95213. _this.loadedParticleSystems = particleSystems;
  95214. _this.loadedSkeletons = skeletons;
  95215. onSuccess();
  95216. }, null, function (scene, message, exception) {
  95217. onError(message, exception);
  95218. });
  95219. };
  95220. return MeshAssetTask;
  95221. }(AbstractAssetTask));
  95222. BABYLON.MeshAssetTask = MeshAssetTask;
  95223. /**
  95224. * Define a task used by {BABYLON.AssetsManager} to load text content
  95225. */
  95226. var TextFileAssetTask = /** @class */ (function (_super) {
  95227. __extends(TextFileAssetTask, _super);
  95228. /**
  95229. * Creates a new TextFileAssetTask object
  95230. * @param name defines the name of the task
  95231. * @param url defines the location of the file to load
  95232. */
  95233. function TextFileAssetTask(
  95234. /**
  95235. * Defines the name of the task
  95236. */
  95237. name,
  95238. /**
  95239. * Defines the location of the file to load
  95240. */
  95241. url) {
  95242. var _this = _super.call(this, name) || this;
  95243. _this.name = name;
  95244. _this.url = url;
  95245. return _this;
  95246. }
  95247. /**
  95248. * Execute the current task
  95249. * @param scene defines the scene where you want your assets to be loaded
  95250. * @param onSuccess is a callback called when the task is successfully executed
  95251. * @param onError is a callback called if an error occurs
  95252. */
  95253. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95254. var _this = this;
  95255. scene._loadFile(this.url, function (data) {
  95256. _this.text = data;
  95257. onSuccess();
  95258. }, undefined, false, false, function (request, exception) {
  95259. if (request) {
  95260. onError(request.status + " " + request.statusText, exception);
  95261. }
  95262. });
  95263. };
  95264. return TextFileAssetTask;
  95265. }(AbstractAssetTask));
  95266. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95267. /**
  95268. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95269. */
  95270. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95271. __extends(BinaryFileAssetTask, _super);
  95272. /**
  95273. * Creates a new BinaryFileAssetTask object
  95274. * @param name defines the name of the new task
  95275. * @param url defines the location of the file to load
  95276. */
  95277. function BinaryFileAssetTask(
  95278. /**
  95279. * Defines the name of the task
  95280. */
  95281. name,
  95282. /**
  95283. * Defines the location of the file to load
  95284. */
  95285. url) {
  95286. var _this = _super.call(this, name) || this;
  95287. _this.name = name;
  95288. _this.url = url;
  95289. return _this;
  95290. }
  95291. /**
  95292. * Execute the current task
  95293. * @param scene defines the scene where you want your assets to be loaded
  95294. * @param onSuccess is a callback called when the task is successfully executed
  95295. * @param onError is a callback called if an error occurs
  95296. */
  95297. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95298. var _this = this;
  95299. scene._loadFile(this.url, function (data) {
  95300. _this.data = data;
  95301. onSuccess();
  95302. }, undefined, true, true, function (request, exception) {
  95303. if (request) {
  95304. onError(request.status + " " + request.statusText, exception);
  95305. }
  95306. });
  95307. };
  95308. return BinaryFileAssetTask;
  95309. }(AbstractAssetTask));
  95310. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95311. /**
  95312. * Define a task used by {BABYLON.AssetsManager} to load images
  95313. */
  95314. var ImageAssetTask = /** @class */ (function (_super) {
  95315. __extends(ImageAssetTask, _super);
  95316. /**
  95317. * Creates a new ImageAssetTask
  95318. * @param name defines the name of the task
  95319. * @param url defines the location of the image to load
  95320. */
  95321. function ImageAssetTask(
  95322. /**
  95323. * Defines the name of the task
  95324. */
  95325. name,
  95326. /**
  95327. * Defines the location of the image to load
  95328. */
  95329. url) {
  95330. var _this = _super.call(this, name) || this;
  95331. _this.name = name;
  95332. _this.url = url;
  95333. return _this;
  95334. }
  95335. /**
  95336. * Execute the current task
  95337. * @param scene defines the scene where you want your assets to be loaded
  95338. * @param onSuccess is a callback called when the task is successfully executed
  95339. * @param onError is a callback called if an error occurs
  95340. */
  95341. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95342. var _this = this;
  95343. var img = new Image();
  95344. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95345. img.onload = function () {
  95346. _this.image = img;
  95347. onSuccess();
  95348. };
  95349. img.onerror = function (err) {
  95350. onError("Error loading image", err);
  95351. };
  95352. img.src = this.url;
  95353. };
  95354. return ImageAssetTask;
  95355. }(AbstractAssetTask));
  95356. BABYLON.ImageAssetTask = ImageAssetTask;
  95357. /**
  95358. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95359. */
  95360. var TextureAssetTask = /** @class */ (function (_super) {
  95361. __extends(TextureAssetTask, _super);
  95362. /**
  95363. * Creates a new TextureAssetTask object
  95364. * @param name defines the name of the task
  95365. * @param url defines the location of the file to load
  95366. * @param noMipmap defines if mipmap should not be generated (default is false)
  95367. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95368. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95369. */
  95370. function TextureAssetTask(
  95371. /**
  95372. * Defines the name of the task
  95373. */
  95374. name,
  95375. /**
  95376. * Defines the location of the file to load
  95377. */
  95378. url,
  95379. /**
  95380. * Defines if mipmap should not be generated (default is false)
  95381. */
  95382. noMipmap,
  95383. /**
  95384. * Defines if texture must be inverted on Y axis (default is false)
  95385. */
  95386. invertY,
  95387. /**
  95388. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95389. */
  95390. samplingMode) {
  95391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95392. var _this = _super.call(this, name) || this;
  95393. _this.name = name;
  95394. _this.url = url;
  95395. _this.noMipmap = noMipmap;
  95396. _this.invertY = invertY;
  95397. _this.samplingMode = samplingMode;
  95398. return _this;
  95399. }
  95400. /**
  95401. * Execute the current task
  95402. * @param scene defines the scene where you want your assets to be loaded
  95403. * @param onSuccess is a callback called when the task is successfully executed
  95404. * @param onError is a callback called if an error occurs
  95405. */
  95406. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95407. var onload = function () {
  95408. onSuccess();
  95409. };
  95410. var onerror = function (message, exception) {
  95411. onError(message, exception);
  95412. };
  95413. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95414. };
  95415. return TextureAssetTask;
  95416. }(AbstractAssetTask));
  95417. BABYLON.TextureAssetTask = TextureAssetTask;
  95418. /**
  95419. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95420. */
  95421. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95422. __extends(CubeTextureAssetTask, _super);
  95423. /**
  95424. * Creates a new CubeTextureAssetTask
  95425. * @param name defines the name of the task
  95426. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95427. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95428. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95429. * @param files defines the explicit list of files (undefined by default)
  95430. */
  95431. function CubeTextureAssetTask(
  95432. /**
  95433. * Defines the name of the task
  95434. */
  95435. name,
  95436. /**
  95437. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95438. */
  95439. url,
  95440. /**
  95441. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95442. */
  95443. extensions,
  95444. /**
  95445. * Defines if mipmaps should not be generated (default is false)
  95446. */
  95447. noMipmap,
  95448. /**
  95449. * Defines the explicit list of files (undefined by default)
  95450. */
  95451. files) {
  95452. var _this = _super.call(this, name) || this;
  95453. _this.name = name;
  95454. _this.url = url;
  95455. _this.extensions = extensions;
  95456. _this.noMipmap = noMipmap;
  95457. _this.files = files;
  95458. return _this;
  95459. }
  95460. /**
  95461. * Execute the current task
  95462. * @param scene defines the scene where you want your assets to be loaded
  95463. * @param onSuccess is a callback called when the task is successfully executed
  95464. * @param onError is a callback called if an error occurs
  95465. */
  95466. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95467. var onload = function () {
  95468. onSuccess();
  95469. };
  95470. var onerror = function (message, exception) {
  95471. onError(message, exception);
  95472. };
  95473. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95474. };
  95475. return CubeTextureAssetTask;
  95476. }(AbstractAssetTask));
  95477. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95478. /**
  95479. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95480. */
  95481. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95482. __extends(HDRCubeTextureAssetTask, _super);
  95483. /**
  95484. * Creates a new HDRCubeTextureAssetTask object
  95485. * @param name defines the name of the task
  95486. * @param url defines the location of the file to load
  95487. * @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.
  95488. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95489. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95490. * @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)
  95491. * @param reserved Internal use only
  95492. */
  95493. function HDRCubeTextureAssetTask(
  95494. /**
  95495. * Defines the name of the task
  95496. */
  95497. name,
  95498. /**
  95499. * Defines the location of the file to load
  95500. */
  95501. url,
  95502. /**
  95503. * Defines the desired size (the more it increases the longer the generation will be)
  95504. */
  95505. size,
  95506. /**
  95507. * Defines if mipmaps should not be generated (default is false)
  95508. */
  95509. noMipmap,
  95510. /**
  95511. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95512. */
  95513. generateHarmonics,
  95514. /**
  95515. * 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)
  95516. */
  95517. gammaSpace,
  95518. /**
  95519. * Internal Use Only
  95520. */
  95521. reserved) {
  95522. if (noMipmap === void 0) { noMipmap = false; }
  95523. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95524. if (gammaSpace === void 0) { gammaSpace = false; }
  95525. if (reserved === void 0) { reserved = false; }
  95526. var _this = _super.call(this, name) || this;
  95527. _this.name = name;
  95528. _this.url = url;
  95529. _this.size = size;
  95530. _this.noMipmap = noMipmap;
  95531. _this.generateHarmonics = generateHarmonics;
  95532. _this.gammaSpace = gammaSpace;
  95533. _this.reserved = reserved;
  95534. return _this;
  95535. }
  95536. /**
  95537. * Execute the current task
  95538. * @param scene defines the scene where you want your assets to be loaded
  95539. * @param onSuccess is a callback called when the task is successfully executed
  95540. * @param onError is a callback called if an error occurs
  95541. */
  95542. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95543. var onload = function () {
  95544. onSuccess();
  95545. };
  95546. var onerror = function (message, exception) {
  95547. onError(message, exception);
  95548. };
  95549. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95550. };
  95551. return HDRCubeTextureAssetTask;
  95552. }(AbstractAssetTask));
  95553. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95554. /**
  95555. * This class can be used to easily import assets into a scene
  95556. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95557. */
  95558. var AssetsManager = /** @class */ (function () {
  95559. /**
  95560. * Creates a new AssetsManager
  95561. * @param scene defines the scene to work on
  95562. */
  95563. function AssetsManager(scene) {
  95564. this._isLoading = false;
  95565. this._tasks = new Array();
  95566. this._waitingTasksCount = 0;
  95567. this._totalTasksCount = 0;
  95568. /**
  95569. * Observable called when all tasks are processed
  95570. */
  95571. this.onTaskSuccessObservable = new BABYLON.Observable();
  95572. /**
  95573. * Observable called when a task had an error
  95574. */
  95575. this.onTaskErrorObservable = new BABYLON.Observable();
  95576. /**
  95577. * Observable called when a task is successful
  95578. */
  95579. this.onTasksDoneObservable = new BABYLON.Observable();
  95580. /**
  95581. * Observable called when a task is done (whatever the result is)
  95582. */
  95583. this.onProgressObservable = new BABYLON.Observable();
  95584. /**
  95585. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95586. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95587. */
  95588. this.useDefaultLoadingScreen = true;
  95589. this._scene = scene;
  95590. }
  95591. /**
  95592. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95593. * @param taskName defines the name of the new task
  95594. * @param meshesNames defines the name of meshes to load
  95595. * @param rootUrl defines the root url to use to locate files
  95596. * @param sceneFilename defines the filename of the scene file
  95597. * @returns a new {BABYLON.MeshAssetTask} object
  95598. */
  95599. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  95600. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  95601. this._tasks.push(task);
  95602. return task;
  95603. };
  95604. /**
  95605. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  95606. * @param taskName defines the name of the new task
  95607. * @param url defines the url of the file to load
  95608. * @returns a new {BABYLON.TextFileAssetTask} object
  95609. */
  95610. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  95611. var task = new TextFileAssetTask(taskName, url);
  95612. this._tasks.push(task);
  95613. return task;
  95614. };
  95615. /**
  95616. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  95617. * @param taskName defines the name of the new task
  95618. * @param url defines the url of the file to load
  95619. * @returns a new {BABYLON.BinaryFileAssetTask} object
  95620. */
  95621. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  95622. var task = new BinaryFileAssetTask(taskName, url);
  95623. this._tasks.push(task);
  95624. return task;
  95625. };
  95626. /**
  95627. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  95628. * @param taskName defines the name of the new task
  95629. * @param url defines the url of the file to load
  95630. * @returns a new {BABYLON.ImageAssetTask} object
  95631. */
  95632. AssetsManager.prototype.addImageTask = function (taskName, url) {
  95633. var task = new ImageAssetTask(taskName, url);
  95634. this._tasks.push(task);
  95635. return task;
  95636. };
  95637. /**
  95638. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  95639. * @param taskName defines the name of the new task
  95640. * @param url defines the url of the file to load
  95641. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95642. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  95643. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  95644. * @returns a new {BABYLON.TextureAssetTask} object
  95645. */
  95646. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  95647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95648. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  95649. this._tasks.push(task);
  95650. return task;
  95651. };
  95652. /**
  95653. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  95654. * @param taskName defines the name of the new task
  95655. * @param url defines the url of the file to load
  95656. * @param extensions defines the extension to use to load the cube map (can be null)
  95657. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95658. * @param files defines the list of files to load (can be null)
  95659. * @returns a new {BABYLON.CubeTextureAssetTask} object
  95660. */
  95661. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  95662. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  95663. this._tasks.push(task);
  95664. return task;
  95665. };
  95666. /**
  95667. *
  95668. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  95669. * @param taskName defines the name of the new task
  95670. * @param url defines the url of the file to load
  95671. * @param size defines the size you want for the cubemap (can be null)
  95672. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95673. * @param generateHarmonics defines if you want to automatically generate (true by default)
  95674. * @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)
  95675. * @param reserved Internal use only
  95676. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  95677. */
  95678. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  95679. if (noMipmap === void 0) { noMipmap = false; }
  95680. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95681. if (gammaSpace === void 0) { gammaSpace = false; }
  95682. if (reserved === void 0) { reserved = false; }
  95683. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  95684. this._tasks.push(task);
  95685. return task;
  95686. };
  95687. /**
  95688. * Remove a task from the assets manager.
  95689. * @param task the task to remove
  95690. */
  95691. AssetsManager.prototype.removeTask = function (task) {
  95692. var index = this._tasks.indexOf(task);
  95693. if (index > -1) {
  95694. this._tasks.splice(index, 1);
  95695. }
  95696. };
  95697. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  95698. this._waitingTasksCount--;
  95699. try {
  95700. if (this.onProgress) {
  95701. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  95702. }
  95703. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  95704. }
  95705. catch (e) {
  95706. BABYLON.Tools.Error("Error running progress callbacks.");
  95707. console.log(e);
  95708. }
  95709. if (this._waitingTasksCount === 0) {
  95710. try {
  95711. if (this.onFinish) {
  95712. this.onFinish(this._tasks);
  95713. }
  95714. // Let's remove successfull tasks
  95715. var currentTasks = this._tasks.slice();
  95716. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  95717. var task = currentTasks_1[_i];
  95718. if (task.taskState === AssetTaskState.DONE) {
  95719. var index = this._tasks.indexOf(task);
  95720. if (index > -1) {
  95721. this._tasks.splice(index, 1);
  95722. }
  95723. }
  95724. }
  95725. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95726. }
  95727. catch (e) {
  95728. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  95729. console.log(e);
  95730. }
  95731. this._isLoading = false;
  95732. this._scene.getEngine().hideLoadingUI();
  95733. }
  95734. };
  95735. AssetsManager.prototype._runTask = function (task) {
  95736. var _this = this;
  95737. var done = function () {
  95738. try {
  95739. if (_this.onTaskSuccess) {
  95740. _this.onTaskSuccess(task);
  95741. }
  95742. _this.onTaskSuccessObservable.notifyObservers(task);
  95743. _this._decreaseWaitingTasksCount(task);
  95744. }
  95745. catch (e) {
  95746. error("Error executing task success callbacks", e);
  95747. }
  95748. };
  95749. var error = function (message, exception) {
  95750. task._setErrorObject(message, exception);
  95751. if (_this.onTaskError) {
  95752. _this.onTaskError(task);
  95753. }
  95754. _this.onTaskErrorObservable.notifyObservers(task);
  95755. _this._decreaseWaitingTasksCount(task);
  95756. };
  95757. task.run(this._scene, done, error);
  95758. };
  95759. /**
  95760. * Reset the {BABYLON.AssetsManager} and remove all tasks
  95761. * @return the current instance of the {BABYLON.AssetsManager}
  95762. */
  95763. AssetsManager.prototype.reset = function () {
  95764. this._isLoading = false;
  95765. this._tasks = new Array();
  95766. return this;
  95767. };
  95768. /**
  95769. * Start the loading process
  95770. * @return the current instance of the {BABYLON.AssetsManager}
  95771. */
  95772. AssetsManager.prototype.load = function () {
  95773. if (this._isLoading) {
  95774. return this;
  95775. }
  95776. this._isLoading = true;
  95777. this._waitingTasksCount = this._tasks.length;
  95778. this._totalTasksCount = this._tasks.length;
  95779. if (this._waitingTasksCount === 0) {
  95780. this._isLoading = false;
  95781. if (this.onFinish) {
  95782. this.onFinish(this._tasks);
  95783. }
  95784. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95785. return this;
  95786. }
  95787. if (this.useDefaultLoadingScreen) {
  95788. this._scene.getEngine().displayLoadingUI();
  95789. }
  95790. for (var index = 0; index < this._tasks.length; index++) {
  95791. var task = this._tasks[index];
  95792. if (task.taskState === AssetTaskState.INIT) {
  95793. this._runTask(task);
  95794. }
  95795. }
  95796. return this;
  95797. };
  95798. return AssetsManager;
  95799. }());
  95800. BABYLON.AssetsManager = AssetsManager;
  95801. })(BABYLON || (BABYLON = {}));
  95802. //# sourceMappingURL=babylon.assetsManager.js.map
  95803. var BABYLON;
  95804. (function (BABYLON) {
  95805. var serializedGeometries = [];
  95806. var serializeGeometry = function (geometry, serializationGeometries) {
  95807. if (serializedGeometries[geometry.id]) {
  95808. return;
  95809. }
  95810. if (geometry.doNotSerialize) {
  95811. return;
  95812. }
  95813. if (geometry instanceof BABYLON.BoxGeometry) {
  95814. serializationGeometries.boxes.push(geometry.serialize());
  95815. }
  95816. else if (geometry instanceof BABYLON.SphereGeometry) {
  95817. serializationGeometries.spheres.push(geometry.serialize());
  95818. }
  95819. else if (geometry instanceof BABYLON.CylinderGeometry) {
  95820. serializationGeometries.cylinders.push(geometry.serialize());
  95821. }
  95822. else if (geometry instanceof BABYLON.TorusGeometry) {
  95823. serializationGeometries.toruses.push(geometry.serialize());
  95824. }
  95825. else if (geometry instanceof BABYLON.GroundGeometry) {
  95826. serializationGeometries.grounds.push(geometry.serialize());
  95827. }
  95828. else if (geometry instanceof BABYLON.Plane) {
  95829. serializationGeometries.planes.push(geometry.serialize());
  95830. }
  95831. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  95832. serializationGeometries.torusKnots.push(geometry.serialize());
  95833. }
  95834. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  95835. throw new Error("Unknown primitive type");
  95836. }
  95837. else {
  95838. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  95839. }
  95840. serializedGeometries[geometry.id] = true;
  95841. };
  95842. var serializeMesh = function (mesh, serializationScene) {
  95843. var serializationObject = {};
  95844. // Geometry
  95845. var geometry = mesh._geometry;
  95846. if (geometry) {
  95847. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  95848. // 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
  95849. serializeGeometry(geometry, serializationScene.geometries);
  95850. }
  95851. }
  95852. // Custom
  95853. if (mesh.serialize) {
  95854. mesh.serialize(serializationObject);
  95855. }
  95856. return serializationObject;
  95857. };
  95858. var finalizeSingleMesh = function (mesh, serializationObject) {
  95859. //only works if the mesh is already loaded
  95860. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95861. //serialize material
  95862. if (mesh.material) {
  95863. if (mesh.material instanceof BABYLON.MultiMaterial) {
  95864. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  95865. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95866. serializationObject.multiMaterials.push(mesh.material.serialize());
  95867. }
  95868. }
  95869. else {
  95870. serializationObject.materials = serializationObject.materials || [];
  95871. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95872. serializationObject.materials.push(mesh.material.serialize());
  95873. }
  95874. }
  95875. }
  95876. //serialize geometry
  95877. var geometry = mesh._geometry;
  95878. if (geometry) {
  95879. if (!serializationObject.geometries) {
  95880. serializationObject.geometries = {};
  95881. serializationObject.geometries.boxes = [];
  95882. serializationObject.geometries.spheres = [];
  95883. serializationObject.geometries.cylinders = [];
  95884. serializationObject.geometries.toruses = [];
  95885. serializationObject.geometries.grounds = [];
  95886. serializationObject.geometries.planes = [];
  95887. serializationObject.geometries.torusKnots = [];
  95888. serializationObject.geometries.vertexData = [];
  95889. }
  95890. serializeGeometry(geometry, serializationObject.geometries);
  95891. }
  95892. // Skeletons
  95893. if (mesh.skeleton) {
  95894. serializationObject.skeletons = serializationObject.skeletons || [];
  95895. serializationObject.skeletons.push(mesh.skeleton.serialize());
  95896. }
  95897. //serialize the actual mesh
  95898. serializationObject.meshes = serializationObject.meshes || [];
  95899. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95900. }
  95901. };
  95902. var SceneSerializer = /** @class */ (function () {
  95903. function SceneSerializer() {
  95904. }
  95905. SceneSerializer.ClearCache = function () {
  95906. serializedGeometries = [];
  95907. };
  95908. SceneSerializer.Serialize = function (scene) {
  95909. var serializationObject = {};
  95910. SceneSerializer.ClearCache();
  95911. // Scene
  95912. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  95913. serializationObject.autoClear = scene.autoClear;
  95914. serializationObject.clearColor = scene.clearColor.asArray();
  95915. serializationObject.ambientColor = scene.ambientColor.asArray();
  95916. serializationObject.gravity = scene.gravity.asArray();
  95917. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  95918. serializationObject.workerCollisions = scene.workerCollisions;
  95919. // Fog
  95920. if (scene.fogMode && scene.fogMode !== 0) {
  95921. serializationObject.fogMode = scene.fogMode;
  95922. serializationObject.fogColor = scene.fogColor.asArray();
  95923. serializationObject.fogStart = scene.fogStart;
  95924. serializationObject.fogEnd = scene.fogEnd;
  95925. serializationObject.fogDensity = scene.fogDensity;
  95926. }
  95927. //Physics
  95928. if (scene.isPhysicsEnabled()) {
  95929. var physicEngine = scene.getPhysicsEngine();
  95930. if (physicEngine) {
  95931. serializationObject.physicsEnabled = true;
  95932. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  95933. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  95934. }
  95935. }
  95936. // Metadata
  95937. if (scene.metadata) {
  95938. serializationObject.metadata = scene.metadata;
  95939. }
  95940. // Morph targets
  95941. serializationObject.morphTargetManagers = [];
  95942. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  95943. var abstractMesh = _a[_i];
  95944. var manager = abstractMesh.morphTargetManager;
  95945. if (manager) {
  95946. serializationObject.morphTargetManagers.push(manager.serialize());
  95947. }
  95948. }
  95949. // Lights
  95950. serializationObject.lights = [];
  95951. var index;
  95952. var light;
  95953. for (index = 0; index < scene.lights.length; index++) {
  95954. light = scene.lights[index];
  95955. if (!light.doNotSerialize) {
  95956. serializationObject.lights.push(light.serialize());
  95957. }
  95958. }
  95959. // Cameras
  95960. serializationObject.cameras = [];
  95961. for (index = 0; index < scene.cameras.length; index++) {
  95962. var camera = scene.cameras[index];
  95963. if (!camera.doNotSerialize) {
  95964. serializationObject.cameras.push(camera.serialize());
  95965. }
  95966. }
  95967. if (scene.activeCamera) {
  95968. serializationObject.activeCameraID = scene.activeCamera.id;
  95969. }
  95970. // Animations
  95971. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  95972. // Materials
  95973. serializationObject.materials = [];
  95974. serializationObject.multiMaterials = [];
  95975. var material;
  95976. for (index = 0; index < scene.materials.length; index++) {
  95977. material = scene.materials[index];
  95978. if (!material.doNotSerialize) {
  95979. serializationObject.materials.push(material.serialize());
  95980. }
  95981. }
  95982. // MultiMaterials
  95983. serializationObject.multiMaterials = [];
  95984. for (index = 0; index < scene.multiMaterials.length; index++) {
  95985. var multiMaterial = scene.multiMaterials[index];
  95986. serializationObject.multiMaterials.push(multiMaterial.serialize());
  95987. }
  95988. // Environment texture
  95989. if (scene.environmentTexture) {
  95990. serializationObject.environmentTexture = scene.environmentTexture.name;
  95991. }
  95992. // Skeletons
  95993. serializationObject.skeletons = [];
  95994. for (index = 0; index < scene.skeletons.length; index++) {
  95995. var skeleton = scene.skeletons[index];
  95996. if (!skeleton.doNotSerialize) {
  95997. serializationObject.skeletons.push(skeleton.serialize());
  95998. }
  95999. }
  96000. // Transform nodes
  96001. serializationObject.transformNodes = [];
  96002. for (index = 0; index < scene.transformNodes.length; index++) {
  96003. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  96004. }
  96005. // Geometries
  96006. serializationObject.geometries = {};
  96007. serializationObject.geometries.boxes = [];
  96008. serializationObject.geometries.spheres = [];
  96009. serializationObject.geometries.cylinders = [];
  96010. serializationObject.geometries.toruses = [];
  96011. serializationObject.geometries.grounds = [];
  96012. serializationObject.geometries.planes = [];
  96013. serializationObject.geometries.torusKnots = [];
  96014. serializationObject.geometries.vertexData = [];
  96015. serializedGeometries = [];
  96016. var geometries = scene.getGeometries();
  96017. for (index = 0; index < geometries.length; index++) {
  96018. var geometry = geometries[index];
  96019. if (geometry.isReady()) {
  96020. serializeGeometry(geometry, serializationObject.geometries);
  96021. }
  96022. }
  96023. // Meshes
  96024. serializationObject.meshes = [];
  96025. for (index = 0; index < scene.meshes.length; index++) {
  96026. var abstractMesh = scene.meshes[index];
  96027. if (abstractMesh instanceof BABYLON.Mesh) {
  96028. var mesh = abstractMesh;
  96029. if (!mesh.doNotSerialize) {
  96030. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96031. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96032. }
  96033. }
  96034. }
  96035. }
  96036. // Particles Systems
  96037. serializationObject.particleSystems = [];
  96038. for (index = 0; index < scene.particleSystems.length; index++) {
  96039. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  96040. }
  96041. // Lens flares
  96042. serializationObject.lensFlareSystems = [];
  96043. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  96044. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  96045. }
  96046. // Shadows
  96047. serializationObject.shadowGenerators = [];
  96048. for (index = 0; index < scene.lights.length; index++) {
  96049. light = scene.lights[index];
  96050. var shadowGenerator = light.getShadowGenerator();
  96051. if (shadowGenerator) {
  96052. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  96053. }
  96054. }
  96055. // Action Manager
  96056. if (scene.actionManager) {
  96057. serializationObject.actions = scene.actionManager.serialize("scene");
  96058. }
  96059. // Audio
  96060. serializationObject.sounds = [];
  96061. for (index = 0; index < scene.soundTracks.length; index++) {
  96062. var soundtrack = scene.soundTracks[index];
  96063. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  96064. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  96065. }
  96066. }
  96067. // Effect layers
  96068. serializationObject.effectLayers = [];
  96069. for (index = 0; index < scene.effectLayers.length; index++) {
  96070. var layer = scene.effectLayers[index];
  96071. if (layer.serialize) {
  96072. serializationObject.effectLayers.push(layer.serialize());
  96073. }
  96074. }
  96075. return serializationObject;
  96076. };
  96077. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  96078. if (withParents === void 0) { withParents = false; }
  96079. if (withChildren === void 0) { withChildren = false; }
  96080. var serializationObject = {};
  96081. SceneSerializer.ClearCache();
  96082. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  96083. if (withParents || withChildren) {
  96084. //deliberate for loop! not for each, appended should be processed as well.
  96085. for (var i = 0; i < toSerialize.length; ++i) {
  96086. if (withChildren) {
  96087. toSerialize[i].getDescendants().forEach(function (node) {
  96088. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  96089. toSerialize.push(node);
  96090. }
  96091. });
  96092. }
  96093. //make sure the array doesn't contain the object already
  96094. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  96095. toSerialize.push(toSerialize[i].parent);
  96096. }
  96097. }
  96098. }
  96099. toSerialize.forEach(function (mesh) {
  96100. finalizeSingleMesh(mesh, serializationObject);
  96101. });
  96102. return serializationObject;
  96103. };
  96104. return SceneSerializer;
  96105. }());
  96106. BABYLON.SceneSerializer = SceneSerializer;
  96107. })(BABYLON || (BABYLON = {}));
  96108. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96109. var BABYLON;
  96110. (function (BABYLON) {
  96111. var ReflectionProbe = /** @class */ (function () {
  96112. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96113. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96114. var _this = this;
  96115. this.name = name;
  96116. this._viewMatrix = BABYLON.Matrix.Identity();
  96117. this._target = BABYLON.Vector3.Zero();
  96118. this._add = BABYLON.Vector3.Zero();
  96119. this._invertYAxis = false;
  96120. this.position = BABYLON.Vector3.Zero();
  96121. this._scene = scene;
  96122. this._scene.reflectionProbes.push(this);
  96123. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96124. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96125. switch (faceIndex) {
  96126. case 0:
  96127. _this._add.copyFromFloats(1, 0, 0);
  96128. break;
  96129. case 1:
  96130. _this._add.copyFromFloats(-1, 0, 0);
  96131. break;
  96132. case 2:
  96133. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96134. break;
  96135. case 3:
  96136. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96137. break;
  96138. case 4:
  96139. _this._add.copyFromFloats(0, 0, 1);
  96140. break;
  96141. case 5:
  96142. _this._add.copyFromFloats(0, 0, -1);
  96143. break;
  96144. }
  96145. if (_this._attachedMesh) {
  96146. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96147. }
  96148. _this.position.addToRef(_this._add, _this._target);
  96149. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96150. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96151. scene._forcedViewPosition = _this.position;
  96152. });
  96153. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96154. scene._forcedViewPosition = null;
  96155. scene.updateTransformMatrix(true);
  96156. });
  96157. if (scene.activeCamera) {
  96158. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96159. }
  96160. }
  96161. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96162. get: function () {
  96163. return this._renderTargetTexture.samples;
  96164. },
  96165. set: function (value) {
  96166. this._renderTargetTexture.samples = value;
  96167. },
  96168. enumerable: true,
  96169. configurable: true
  96170. });
  96171. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96172. get: function () {
  96173. return this._renderTargetTexture.refreshRate;
  96174. },
  96175. set: function (value) {
  96176. this._renderTargetTexture.refreshRate = value;
  96177. },
  96178. enumerable: true,
  96179. configurable: true
  96180. });
  96181. ReflectionProbe.prototype.getScene = function () {
  96182. return this._scene;
  96183. };
  96184. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96185. get: function () {
  96186. return this._renderTargetTexture;
  96187. },
  96188. enumerable: true,
  96189. configurable: true
  96190. });
  96191. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96192. get: function () {
  96193. return this._renderTargetTexture.renderList;
  96194. },
  96195. enumerable: true,
  96196. configurable: true
  96197. });
  96198. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96199. this._attachedMesh = mesh;
  96200. };
  96201. /**
  96202. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96203. *
  96204. * @param renderingGroupId The rendering group id corresponding to its index
  96205. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96206. */
  96207. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96208. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96209. };
  96210. ReflectionProbe.prototype.dispose = function () {
  96211. var index = this._scene.reflectionProbes.indexOf(this);
  96212. if (index !== -1) {
  96213. // Remove from the scene if found
  96214. this._scene.reflectionProbes.splice(index, 1);
  96215. }
  96216. if (this._renderTargetTexture) {
  96217. this._renderTargetTexture.dispose();
  96218. this._renderTargetTexture = null;
  96219. }
  96220. };
  96221. return ReflectionProbe;
  96222. }());
  96223. BABYLON.ReflectionProbe = ReflectionProbe;
  96224. })(BABYLON || (BABYLON = {}));
  96225. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96226. var BABYLON;
  96227. (function (BABYLON) {
  96228. var Layer = /** @class */ (function () {
  96229. function Layer(name, imgUrl, scene, isBackground, color) {
  96230. this.name = name;
  96231. this.scale = new BABYLON.Vector2(1, 1);
  96232. this.offset = new BABYLON.Vector2(0, 0);
  96233. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96234. this.layerMask = 0x0FFFFFFF;
  96235. this._vertexBuffers = {};
  96236. // Events
  96237. /**
  96238. * An event triggered when the layer is disposed.
  96239. */
  96240. this.onDisposeObservable = new BABYLON.Observable();
  96241. /**
  96242. * An event triggered before rendering the scene
  96243. */
  96244. this.onBeforeRenderObservable = new BABYLON.Observable();
  96245. /**
  96246. * An event triggered after rendering the scene
  96247. */
  96248. this.onAfterRenderObservable = new BABYLON.Observable();
  96249. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96250. this.isBackground = isBackground === undefined ? true : isBackground;
  96251. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96252. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96253. this._scene.layers.push(this);
  96254. var engine = this._scene.getEngine();
  96255. // VBO
  96256. var vertices = [];
  96257. vertices.push(1, 1);
  96258. vertices.push(-1, 1);
  96259. vertices.push(-1, -1);
  96260. vertices.push(1, -1);
  96261. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96262. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96263. this._createIndexBuffer();
  96264. // Effects
  96265. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96266. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96267. }
  96268. Object.defineProperty(Layer.prototype, "onDispose", {
  96269. set: function (callback) {
  96270. if (this._onDisposeObserver) {
  96271. this.onDisposeObservable.remove(this._onDisposeObserver);
  96272. }
  96273. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96274. },
  96275. enumerable: true,
  96276. configurable: true
  96277. });
  96278. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96279. set: function (callback) {
  96280. if (this._onBeforeRenderObserver) {
  96281. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96282. }
  96283. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96284. },
  96285. enumerable: true,
  96286. configurable: true
  96287. });
  96288. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96289. set: function (callback) {
  96290. if (this._onAfterRenderObserver) {
  96291. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96292. }
  96293. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96294. },
  96295. enumerable: true,
  96296. configurable: true
  96297. });
  96298. Layer.prototype._createIndexBuffer = function () {
  96299. var engine = this._scene.getEngine();
  96300. // Indices
  96301. var indices = [];
  96302. indices.push(0);
  96303. indices.push(1);
  96304. indices.push(2);
  96305. indices.push(0);
  96306. indices.push(2);
  96307. indices.push(3);
  96308. this._indexBuffer = engine.createIndexBuffer(indices);
  96309. };
  96310. Layer.prototype._rebuild = function () {
  96311. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96312. if (vb) {
  96313. vb._rebuild();
  96314. }
  96315. this._createIndexBuffer();
  96316. };
  96317. Layer.prototype.render = function () {
  96318. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96319. // Check
  96320. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96321. return;
  96322. var engine = this._scene.getEngine();
  96323. this.onBeforeRenderObservable.notifyObservers(this);
  96324. // Render
  96325. engine.enableEffect(currentEffect);
  96326. engine.setState(false);
  96327. // Texture
  96328. currentEffect.setTexture("textureSampler", this.texture);
  96329. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96330. // Color
  96331. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96332. // Scale / offset
  96333. currentEffect.setVector2("offset", this.offset);
  96334. currentEffect.setVector2("scale", this.scale);
  96335. // VBOs
  96336. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96337. // Draw order
  96338. if (!this.alphaTest) {
  96339. engine.setAlphaMode(this.alphaBlendingMode);
  96340. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96341. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96342. }
  96343. else {
  96344. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96345. }
  96346. this.onAfterRenderObservable.notifyObservers(this);
  96347. };
  96348. Layer.prototype.dispose = function () {
  96349. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96350. if (vertexBuffer) {
  96351. vertexBuffer.dispose();
  96352. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96353. }
  96354. if (this._indexBuffer) {
  96355. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96356. this._indexBuffer = null;
  96357. }
  96358. if (this.texture) {
  96359. this.texture.dispose();
  96360. this.texture = null;
  96361. }
  96362. // Remove from scene
  96363. var index = this._scene.layers.indexOf(this);
  96364. this._scene.layers.splice(index, 1);
  96365. // Callback
  96366. this.onDisposeObservable.notifyObservers(this);
  96367. this.onDisposeObservable.clear();
  96368. this.onAfterRenderObservable.clear();
  96369. this.onBeforeRenderObservable.clear();
  96370. };
  96371. return Layer;
  96372. }());
  96373. BABYLON.Layer = Layer;
  96374. })(BABYLON || (BABYLON = {}));
  96375. //# sourceMappingURL=babylon.layer.js.map
  96376. var BABYLON;
  96377. (function (BABYLON) {
  96378. var TextureTools = /** @class */ (function () {
  96379. function TextureTools() {
  96380. }
  96381. /**
  96382. * Uses the GPU to create a copy texture rescaled at a given size
  96383. * @param texture Texture to copy from
  96384. * @param width Desired width
  96385. * @param height Desired height
  96386. * @return Generated texture
  96387. */
  96388. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96389. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96390. var scene = texture.getScene();
  96391. var engine = scene.getEngine();
  96392. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96393. rtt.wrapU = texture.wrapU;
  96394. rtt.wrapV = texture.wrapV;
  96395. rtt.uOffset = texture.uOffset;
  96396. rtt.vOffset = texture.vOffset;
  96397. rtt.uScale = texture.uScale;
  96398. rtt.vScale = texture.vScale;
  96399. rtt.uAng = texture.uAng;
  96400. rtt.vAng = texture.vAng;
  96401. rtt.wAng = texture.wAng;
  96402. rtt.coordinatesIndex = texture.coordinatesIndex;
  96403. rtt.level = texture.level;
  96404. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96405. rtt._texture.isReady = false;
  96406. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96407. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96408. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96409. passPostProcess.getEffect().executeWhenCompiled(function () {
  96410. passPostProcess.onApply = function (effect) {
  96411. effect.setTexture("textureSampler", texture);
  96412. };
  96413. var internalTexture = rtt.getInternalTexture();
  96414. if (internalTexture) {
  96415. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96416. engine.unBindFramebuffer(internalTexture);
  96417. rtt.disposeFramebufferObjects();
  96418. passPostProcess.dispose();
  96419. internalTexture.isReady = true;
  96420. }
  96421. });
  96422. return rtt;
  96423. };
  96424. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96425. if (!scene._environmentBRDFTexture) {
  96426. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96427. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96428. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96429. scene._environmentBRDFTexture = texture;
  96430. }
  96431. return scene._environmentBRDFTexture;
  96432. };
  96433. 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=";
  96434. return TextureTools;
  96435. }());
  96436. BABYLON.TextureTools = TextureTools;
  96437. })(BABYLON || (BABYLON = {}));
  96438. //# sourceMappingURL=babylon.textureTools.js.map
  96439. var BABYLON;
  96440. (function (BABYLON) {
  96441. var FramingBehavior = /** @class */ (function () {
  96442. function FramingBehavior() {
  96443. this._mode = FramingBehavior.FitFrustumSidesMode;
  96444. this._radiusScale = 1.0;
  96445. this._positionScale = 0.5;
  96446. this._defaultElevation = 0.3;
  96447. this._elevationReturnTime = 1500;
  96448. this._elevationReturnWaitTime = 1000;
  96449. this._zoomStopsAnimation = false;
  96450. this._framingTime = 1500;
  96451. this._isPointerDown = false;
  96452. this._lastInteractionTime = -Infinity;
  96453. // Framing control
  96454. this._animatables = new Array();
  96455. this._betaIsAnimating = false;
  96456. }
  96457. Object.defineProperty(FramingBehavior.prototype, "name", {
  96458. get: function () {
  96459. return "Framing";
  96460. },
  96461. enumerable: true,
  96462. configurable: true
  96463. });
  96464. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96465. /**
  96466. * Gets current mode used by the behavior.
  96467. */
  96468. get: function () {
  96469. return this._mode;
  96470. },
  96471. /**
  96472. * Sets the current mode used by the behavior
  96473. */
  96474. set: function (mode) {
  96475. this._mode = mode;
  96476. },
  96477. enumerable: true,
  96478. configurable: true
  96479. });
  96480. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96481. /**
  96482. * Gets the scale applied to the radius
  96483. */
  96484. get: function () {
  96485. return this._radiusScale;
  96486. },
  96487. /**
  96488. * Sets the scale applied to the radius (1 by default)
  96489. */
  96490. set: function (radius) {
  96491. this._radiusScale = radius;
  96492. },
  96493. enumerable: true,
  96494. configurable: true
  96495. });
  96496. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96497. /**
  96498. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96499. */
  96500. get: function () {
  96501. return this._positionScale;
  96502. },
  96503. /**
  96504. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96505. */
  96506. set: function (scale) {
  96507. this._positionScale = scale;
  96508. },
  96509. enumerable: true,
  96510. configurable: true
  96511. });
  96512. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96513. /**
  96514. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96515. * behaviour is triggered, in radians.
  96516. */
  96517. get: function () {
  96518. return this._defaultElevation;
  96519. },
  96520. /**
  96521. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96522. * behaviour is triggered, in radians.
  96523. */
  96524. set: function (elevation) {
  96525. this._defaultElevation = elevation;
  96526. },
  96527. enumerable: true,
  96528. configurable: true
  96529. });
  96530. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96531. /**
  96532. * Gets the time (in milliseconds) taken to return to the default beta position.
  96533. * Negative value indicates camera should not return to default.
  96534. */
  96535. get: function () {
  96536. return this._elevationReturnTime;
  96537. },
  96538. /**
  96539. * Sets the time (in milliseconds) taken to return to the default beta position.
  96540. * Negative value indicates camera should not return to default.
  96541. */
  96542. set: function (speed) {
  96543. this._elevationReturnTime = speed;
  96544. },
  96545. enumerable: true,
  96546. configurable: true
  96547. });
  96548. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96549. /**
  96550. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96551. */
  96552. get: function () {
  96553. return this._elevationReturnWaitTime;
  96554. },
  96555. /**
  96556. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96557. */
  96558. set: function (time) {
  96559. this._elevationReturnWaitTime = time;
  96560. },
  96561. enumerable: true,
  96562. configurable: true
  96563. });
  96564. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96565. /**
  96566. * Gets the flag that indicates if user zooming should stop animation.
  96567. */
  96568. get: function () {
  96569. return this._zoomStopsAnimation;
  96570. },
  96571. /**
  96572. * Sets the flag that indicates if user zooming should stop animation.
  96573. */
  96574. set: function (flag) {
  96575. this._zoomStopsAnimation = flag;
  96576. },
  96577. enumerable: true,
  96578. configurable: true
  96579. });
  96580. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96581. /**
  96582. * Gets the transition time when framing the mesh, in milliseconds
  96583. */
  96584. get: function () {
  96585. return this._framingTime;
  96586. },
  96587. /**
  96588. * Sets the transition time when framing the mesh, in milliseconds
  96589. */
  96590. set: function (time) {
  96591. this._framingTime = time;
  96592. },
  96593. enumerable: true,
  96594. configurable: true
  96595. });
  96596. FramingBehavior.prototype.init = function () {
  96597. // Do notihng
  96598. };
  96599. FramingBehavior.prototype.attach = function (camera) {
  96600. var _this = this;
  96601. this._attachedCamera = camera;
  96602. var scene = this._attachedCamera.getScene();
  96603. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  96604. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96605. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96606. _this._isPointerDown = true;
  96607. return;
  96608. }
  96609. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96610. _this._isPointerDown = false;
  96611. }
  96612. });
  96613. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96614. if (mesh) {
  96615. _this.zoomOnMesh(mesh);
  96616. }
  96617. });
  96618. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96619. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96620. _this._applyUserInteraction();
  96621. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  96622. // back to the default position after a given timeout
  96623. _this._maintainCameraAboveGround();
  96624. });
  96625. };
  96626. FramingBehavior.prototype.detach = function () {
  96627. if (!this._attachedCamera) {
  96628. return;
  96629. }
  96630. var scene = this._attachedCamera.getScene();
  96631. if (this._onPrePointerObservableObserver) {
  96632. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96633. }
  96634. if (this._onAfterCheckInputsObserver) {
  96635. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96636. }
  96637. if (this._onMeshTargetChangedObserver) {
  96638. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96639. }
  96640. this._attachedCamera = null;
  96641. };
  96642. /**
  96643. * Targets the given mesh and updates zoom level accordingly.
  96644. * @param mesh The mesh to target.
  96645. * @param radius Optional. If a cached radius position already exists, overrides default.
  96646. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96647. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96648. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96649. */
  96650. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96651. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96652. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96653. mesh.computeWorldMatrix(true);
  96654. var boundingBox = mesh.getBoundingInfo().boundingBox;
  96655. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  96656. };
  96657. /**
  96658. * Targets the given mesh with its children and updates zoom level accordingly.
  96659. * @param mesh The mesh to target.
  96660. * @param radius Optional. If a cached radius position already exists, overrides default.
  96661. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96662. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96663. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96664. */
  96665. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96666. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96667. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96668. mesh.computeWorldMatrix(true);
  96669. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  96670. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  96671. };
  96672. /**
  96673. * Targets the given meshes with their children and updates zoom level accordingly.
  96674. * @param meshes The mesh to target.
  96675. * @param radius Optional. If a cached radius position already exists, overrides default.
  96676. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96677. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96678. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96679. */
  96680. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  96681. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96682. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96683. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  96684. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  96685. for (var i = 0; i < meshes.length; i++) {
  96686. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  96687. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  96688. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  96689. }
  96690. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  96691. };
  96692. /**
  96693. * Targets the given mesh and updates zoom level accordingly.
  96694. * @param mesh The mesh to target.
  96695. * @param radius Optional. If a cached radius position already exists, overrides default.
  96696. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96697. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96698. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96699. */
  96700. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  96701. var _this = this;
  96702. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96703. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96704. var zoomTarget;
  96705. if (!this._attachedCamera) {
  96706. return;
  96707. }
  96708. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  96709. var bottom = minimumWorld.y;
  96710. var top = maximumWorld.y;
  96711. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  96712. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  96713. if (focusOnOriginXZ) {
  96714. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  96715. }
  96716. else {
  96717. var centerWorld = minimumWorld.add(radiusWorld);
  96718. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  96719. }
  96720. if (!this._vectorTransition) {
  96721. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  96722. }
  96723. this._betaIsAnimating = true;
  96724. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  96725. if (animatable) {
  96726. this._animatables.push(animatable);
  96727. }
  96728. // sets the radius and lower radius bounds
  96729. // Small delta ensures camera is not always at lower zoom limit.
  96730. var radius = 0;
  96731. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  96732. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96733. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  96734. radius = position;
  96735. }
  96736. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96737. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96738. if (this._attachedCamera.lowerRadiusLimit === null) {
  96739. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  96740. }
  96741. }
  96742. // Set sensibilities
  96743. var extend = maximumWorld.subtract(minimumWorld).length();
  96744. this._attachedCamera.panningSensibility = 5000 / extend;
  96745. this._attachedCamera.wheelPrecision = 100 / radius;
  96746. // transition to new radius
  96747. if (!this._radiusTransition) {
  96748. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96749. }
  96750. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  96751. _this.stopAllAnimations();
  96752. if (onAnimationEnd) {
  96753. onAnimationEnd();
  96754. }
  96755. if (_this._attachedCamera) {
  96756. _this._attachedCamera.storeState();
  96757. }
  96758. });
  96759. if (animatable) {
  96760. this._animatables.push(animatable);
  96761. }
  96762. };
  96763. /**
  96764. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  96765. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  96766. * frustum width.
  96767. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  96768. * to fully enclose the mesh in the viewing frustum.
  96769. */
  96770. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  96771. var size = maximumWorld.subtract(minimumWorld);
  96772. var boxVectorGlobalDiagonal = size.length();
  96773. var frustumSlope = this._getFrustumSlope();
  96774. // Formula for setting distance
  96775. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  96776. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  96777. // Horizon distance
  96778. var radius = radiusWithoutFraming * this._radiusScale;
  96779. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  96780. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  96781. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  96782. var camera = this._attachedCamera;
  96783. if (!camera) {
  96784. return 0;
  96785. }
  96786. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96787. // Don't exceed the requested limit
  96788. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  96789. }
  96790. // Don't exceed the upper radius limit
  96791. if (camera.upperRadiusLimit) {
  96792. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  96793. }
  96794. return distance;
  96795. };
  96796. /**
  96797. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  96798. * is automatically returned to its default position (expected to be above ground plane).
  96799. */
  96800. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  96801. var _this = this;
  96802. if (this._elevationReturnTime < 0) {
  96803. return;
  96804. }
  96805. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  96806. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  96807. var limitBeta = Math.PI * 0.5;
  96808. // Bring the camera back up if below the ground plane
  96809. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  96810. this._betaIsAnimating = true;
  96811. //Transition to new position
  96812. this.stopAllAnimations();
  96813. if (!this._betaTransition) {
  96814. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96815. }
  96816. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  96817. _this._clearAnimationLocks();
  96818. _this.stopAllAnimations();
  96819. });
  96820. if (animatabe) {
  96821. this._animatables.push(animatabe);
  96822. }
  96823. }
  96824. };
  96825. /**
  96826. * Returns the frustum slope based on the canvas ratio and camera FOV
  96827. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  96828. */
  96829. FramingBehavior.prototype._getFrustumSlope = function () {
  96830. // Calculate the viewport ratio
  96831. // Aspect Ratio is Height/Width.
  96832. var camera = this._attachedCamera;
  96833. if (!camera) {
  96834. return BABYLON.Vector2.Zero();
  96835. }
  96836. var engine = camera.getScene().getEngine();
  96837. var aspectRatio = engine.getAspectRatio(camera);
  96838. // Camera FOV is the vertical field of view (top-bottom) in radians.
  96839. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  96840. var frustumSlopeY = Math.tan(camera.fov / 2);
  96841. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  96842. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  96843. // along the forward vector.
  96844. var frustumSlopeX = frustumSlopeY * aspectRatio;
  96845. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  96846. };
  96847. /**
  96848. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  96849. */
  96850. FramingBehavior.prototype._clearAnimationLocks = function () {
  96851. this._betaIsAnimating = false;
  96852. };
  96853. /**
  96854. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  96855. */
  96856. FramingBehavior.prototype._applyUserInteraction = function () {
  96857. if (this.isUserIsMoving) {
  96858. this._lastInteractionTime = BABYLON.Tools.Now;
  96859. this.stopAllAnimations();
  96860. this._clearAnimationLocks();
  96861. }
  96862. };
  96863. /**
  96864. * Stops and removes all animations that have been applied to the camera
  96865. */
  96866. FramingBehavior.prototype.stopAllAnimations = function () {
  96867. if (this._attachedCamera) {
  96868. this._attachedCamera.animations = [];
  96869. }
  96870. while (this._animatables.length) {
  96871. if (this._animatables[0]) {
  96872. this._animatables[0].onAnimationEnd = null;
  96873. this._animatables[0].stop();
  96874. }
  96875. this._animatables.shift();
  96876. }
  96877. };
  96878. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  96879. /**
  96880. * Gets a value indicating if the user is moving the camera
  96881. */
  96882. get: function () {
  96883. if (!this._attachedCamera) {
  96884. return false;
  96885. }
  96886. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  96887. this._attachedCamera.inertialBetaOffset !== 0 ||
  96888. this._attachedCamera.inertialRadiusOffset !== 0 ||
  96889. this._attachedCamera.inertialPanningX !== 0 ||
  96890. this._attachedCamera.inertialPanningY !== 0 ||
  96891. this._isPointerDown;
  96892. },
  96893. enumerable: true,
  96894. configurable: true
  96895. });
  96896. /**
  96897. * The easing function used by animations
  96898. */
  96899. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  96900. /**
  96901. * The easing mode used by animations
  96902. */
  96903. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  96904. // Statics
  96905. /**
  96906. * The camera can move all the way towards the mesh.
  96907. */
  96908. FramingBehavior.IgnoreBoundsSizeMode = 0;
  96909. /**
  96910. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  96911. */
  96912. FramingBehavior.FitFrustumSidesMode = 1;
  96913. return FramingBehavior;
  96914. }());
  96915. BABYLON.FramingBehavior = FramingBehavior;
  96916. })(BABYLON || (BABYLON = {}));
  96917. //# sourceMappingURL=babylon.framingBehavior.js.map
  96918. var BABYLON;
  96919. (function (BABYLON) {
  96920. /**
  96921. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  96922. */
  96923. var BouncingBehavior = /** @class */ (function () {
  96924. function BouncingBehavior() {
  96925. /**
  96926. * The duration of the animation, in milliseconds
  96927. */
  96928. this.transitionDuration = 450;
  96929. /**
  96930. * Length of the distance animated by the transition when lower radius is reached
  96931. */
  96932. this.lowerRadiusTransitionRange = 2;
  96933. /**
  96934. * Length of the distance animated by the transition when upper radius is reached
  96935. */
  96936. this.upperRadiusTransitionRange = -2;
  96937. this._autoTransitionRange = false;
  96938. // Animations
  96939. this._radiusIsAnimating = false;
  96940. this._radiusBounceTransition = null;
  96941. this._animatables = new Array();
  96942. }
  96943. Object.defineProperty(BouncingBehavior.prototype, "name", {
  96944. get: function () {
  96945. return "Bouncing";
  96946. },
  96947. enumerable: true,
  96948. configurable: true
  96949. });
  96950. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  96951. /**
  96952. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96953. */
  96954. get: function () {
  96955. return this._autoTransitionRange;
  96956. },
  96957. /**
  96958. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96959. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  96960. */
  96961. set: function (value) {
  96962. var _this = this;
  96963. if (this._autoTransitionRange === value) {
  96964. return;
  96965. }
  96966. this._autoTransitionRange = value;
  96967. var camera = this._attachedCamera;
  96968. if (!camera) {
  96969. return;
  96970. }
  96971. if (value) {
  96972. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96973. if (!mesh) {
  96974. return;
  96975. }
  96976. mesh.computeWorldMatrix(true);
  96977. var diagonal = mesh.getBoundingInfo().diagonalLength;
  96978. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  96979. _this.upperRadiusTransitionRange = diagonal * 0.05;
  96980. });
  96981. }
  96982. else if (this._onMeshTargetChangedObserver) {
  96983. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96984. }
  96985. },
  96986. enumerable: true,
  96987. configurable: true
  96988. });
  96989. BouncingBehavior.prototype.init = function () {
  96990. // Do notihng
  96991. };
  96992. BouncingBehavior.prototype.attach = function (camera) {
  96993. var _this = this;
  96994. this._attachedCamera = camera;
  96995. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96996. if (!_this._attachedCamera) {
  96997. return;
  96998. }
  96999. // Add the bounce animation to the lower radius limit
  97000. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  97001. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  97002. }
  97003. // Add the bounce animation to the upper radius limit
  97004. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  97005. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  97006. }
  97007. });
  97008. };
  97009. BouncingBehavior.prototype.detach = function () {
  97010. if (!this._attachedCamera) {
  97011. return;
  97012. }
  97013. if (this._onAfterCheckInputsObserver) {
  97014. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97015. }
  97016. if (this._onMeshTargetChangedObserver) {
  97017. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97018. }
  97019. this._attachedCamera = null;
  97020. };
  97021. /**
  97022. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  97023. * @param radiusLimit The limit to check against.
  97024. * @return Bool to indicate if at limit.
  97025. */
  97026. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  97027. if (!this._attachedCamera) {
  97028. return false;
  97029. }
  97030. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  97031. return true;
  97032. }
  97033. return false;
  97034. };
  97035. /**
  97036. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  97037. * @param radiusDelta The delta by which to animate to. Can be negative.
  97038. */
  97039. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  97040. var _this = this;
  97041. if (!this._attachedCamera) {
  97042. return;
  97043. }
  97044. if (!this._radiusBounceTransition) {
  97045. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  97046. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  97047. }
  97048. // Prevent zoom until bounce has completed
  97049. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  97050. this._attachedCamera.wheelPrecision = Infinity;
  97051. this._attachedCamera.inertialRadiusOffset = 0;
  97052. // Animate to the radius limit
  97053. this.stopAllAnimations();
  97054. this._radiusIsAnimating = true;
  97055. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  97056. if (animatable) {
  97057. this._animatables.push(animatable);
  97058. }
  97059. };
  97060. /**
  97061. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  97062. */
  97063. BouncingBehavior.prototype._clearAnimationLocks = function () {
  97064. this._radiusIsAnimating = false;
  97065. if (this._attachedCamera) {
  97066. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  97067. }
  97068. };
  97069. /**
  97070. * Stops and removes all animations that have been applied to the camera
  97071. */
  97072. BouncingBehavior.prototype.stopAllAnimations = function () {
  97073. if (this._attachedCamera) {
  97074. this._attachedCamera.animations = [];
  97075. }
  97076. while (this._animatables.length) {
  97077. this._animatables[0].onAnimationEnd = null;
  97078. this._animatables[0].stop();
  97079. this._animatables.shift();
  97080. }
  97081. };
  97082. /**
  97083. * The easing function used by animations
  97084. */
  97085. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  97086. /**
  97087. * The easing mode used by animations
  97088. */
  97089. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  97090. return BouncingBehavior;
  97091. }());
  97092. BABYLON.BouncingBehavior = BouncingBehavior;
  97093. })(BABYLON || (BABYLON = {}));
  97094. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  97095. var BABYLON;
  97096. (function (BABYLON) {
  97097. var AutoRotationBehavior = /** @class */ (function () {
  97098. function AutoRotationBehavior() {
  97099. this._zoomStopsAnimation = false;
  97100. this._idleRotationSpeed = 0.05;
  97101. this._idleRotationWaitTime = 2000;
  97102. this._idleRotationSpinupTime = 2000;
  97103. this._isPointerDown = false;
  97104. this._lastFrameTime = null;
  97105. this._lastInteractionTime = -Infinity;
  97106. this._cameraRotationSpeed = 0;
  97107. this._lastFrameRadius = 0;
  97108. }
  97109. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97110. get: function () {
  97111. return "AutoRotation";
  97112. },
  97113. enumerable: true,
  97114. configurable: true
  97115. });
  97116. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97117. /**
  97118. * Gets the flag that indicates if user zooming should stop animation.
  97119. */
  97120. get: function () {
  97121. return this._zoomStopsAnimation;
  97122. },
  97123. /**
  97124. * Sets the flag that indicates if user zooming should stop animation.
  97125. */
  97126. set: function (flag) {
  97127. this._zoomStopsAnimation = flag;
  97128. },
  97129. enumerable: true,
  97130. configurable: true
  97131. });
  97132. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97133. /**
  97134. * Gets the default speed at which the camera rotates around the model.
  97135. */
  97136. get: function () {
  97137. return this._idleRotationSpeed;
  97138. },
  97139. /**
  97140. * Sets the default speed at which the camera rotates around the model.
  97141. */
  97142. set: function (speed) {
  97143. this._idleRotationSpeed = speed;
  97144. },
  97145. enumerable: true,
  97146. configurable: true
  97147. });
  97148. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97149. /**
  97150. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97151. */
  97152. get: function () {
  97153. return this._idleRotationWaitTime;
  97154. },
  97155. /**
  97156. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97157. */
  97158. set: function (time) {
  97159. this._idleRotationWaitTime = time;
  97160. },
  97161. enumerable: true,
  97162. configurable: true
  97163. });
  97164. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97165. /**
  97166. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97167. */
  97168. get: function () {
  97169. return this._idleRotationSpinupTime;
  97170. },
  97171. /**
  97172. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97173. */
  97174. set: function (time) {
  97175. this._idleRotationSpinupTime = time;
  97176. },
  97177. enumerable: true,
  97178. configurable: true
  97179. });
  97180. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97181. /**
  97182. * Gets a value indicating if the camera is currently rotating because of this behavior
  97183. */
  97184. get: function () {
  97185. return Math.abs(this._cameraRotationSpeed) > 0;
  97186. },
  97187. enumerable: true,
  97188. configurable: true
  97189. });
  97190. AutoRotationBehavior.prototype.init = function () {
  97191. // Do notihng
  97192. };
  97193. AutoRotationBehavior.prototype.attach = function (camera) {
  97194. var _this = this;
  97195. this._attachedCamera = camera;
  97196. var scene = this._attachedCamera.getScene();
  97197. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97198. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97199. _this._isPointerDown = true;
  97200. return;
  97201. }
  97202. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97203. _this._isPointerDown = false;
  97204. }
  97205. });
  97206. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97207. var now = BABYLON.Tools.Now;
  97208. var dt = 0;
  97209. if (_this._lastFrameTime != null) {
  97210. dt = now - _this._lastFrameTime;
  97211. }
  97212. _this._lastFrameTime = now;
  97213. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97214. _this._applyUserInteraction();
  97215. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97216. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97217. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97218. // Step camera rotation by rotation speed
  97219. if (_this._attachedCamera) {
  97220. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97221. }
  97222. });
  97223. };
  97224. AutoRotationBehavior.prototype.detach = function () {
  97225. if (!this._attachedCamera) {
  97226. return;
  97227. }
  97228. var scene = this._attachedCamera.getScene();
  97229. if (this._onPrePointerObservableObserver) {
  97230. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97231. }
  97232. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97233. this._attachedCamera = null;
  97234. };
  97235. /**
  97236. * Returns true if user is scrolling.
  97237. * @return true if user is scrolling.
  97238. */
  97239. AutoRotationBehavior.prototype._userIsZooming = function () {
  97240. if (!this._attachedCamera) {
  97241. return false;
  97242. }
  97243. return this._attachedCamera.inertialRadiusOffset !== 0;
  97244. };
  97245. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97246. if (!this._attachedCamera) {
  97247. return false;
  97248. }
  97249. var zoomHasHitLimit = false;
  97250. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97251. zoomHasHitLimit = true;
  97252. }
  97253. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97254. this._lastFrameRadius = this._attachedCamera.radius;
  97255. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97256. };
  97257. /**
  97258. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97259. */
  97260. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97261. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97262. this._lastInteractionTime = BABYLON.Tools.Now;
  97263. }
  97264. };
  97265. // Tools
  97266. AutoRotationBehavior.prototype._userIsMoving = function () {
  97267. if (!this._attachedCamera) {
  97268. return false;
  97269. }
  97270. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97271. this._attachedCamera.inertialBetaOffset !== 0 ||
  97272. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97273. this._attachedCamera.inertialPanningX !== 0 ||
  97274. this._attachedCamera.inertialPanningY !== 0 ||
  97275. this._isPointerDown;
  97276. };
  97277. return AutoRotationBehavior;
  97278. }());
  97279. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97280. })(BABYLON || (BABYLON = {}));
  97281. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97282. var BABYLON;
  97283. (function (BABYLON) {
  97284. var NullEngineOptions = /** @class */ (function () {
  97285. function NullEngineOptions() {
  97286. this.renderWidth = 512;
  97287. this.renderHeight = 256;
  97288. this.textureSize = 512;
  97289. this.deterministicLockstep = false;
  97290. this.lockstepMaxSteps = 4;
  97291. }
  97292. return NullEngineOptions;
  97293. }());
  97294. BABYLON.NullEngineOptions = NullEngineOptions;
  97295. /**
  97296. * The null engine class provides support for headless version of babylon.js.
  97297. * This can be used in server side scenario or for testing purposes
  97298. */
  97299. var NullEngine = /** @class */ (function (_super) {
  97300. __extends(NullEngine, _super);
  97301. function NullEngine(options) {
  97302. if (options === void 0) { options = new NullEngineOptions(); }
  97303. var _this = _super.call(this, null) || this;
  97304. if (options.deterministicLockstep === undefined) {
  97305. options.deterministicLockstep = false;
  97306. }
  97307. if (options.lockstepMaxSteps === undefined) {
  97308. options.lockstepMaxSteps = 4;
  97309. }
  97310. _this._options = options;
  97311. // Init caps
  97312. // We consider we are on a webgl1 capable device
  97313. _this._caps = new BABYLON.EngineCapabilities();
  97314. _this._caps.maxTexturesImageUnits = 16;
  97315. _this._caps.maxVertexTextureImageUnits = 16;
  97316. _this._caps.maxTextureSize = 512;
  97317. _this._caps.maxCubemapTextureSize = 512;
  97318. _this._caps.maxRenderTextureSize = 512;
  97319. _this._caps.maxVertexAttribs = 16;
  97320. _this._caps.maxVaryingVectors = 16;
  97321. _this._caps.maxFragmentUniformVectors = 16;
  97322. _this._caps.maxVertexUniformVectors = 16;
  97323. // Extensions
  97324. _this._caps.standardDerivatives = false;
  97325. _this._caps.astc = null;
  97326. _this._caps.s3tc = null;
  97327. _this._caps.pvrtc = null;
  97328. _this._caps.etc1 = null;
  97329. _this._caps.etc2 = null;
  97330. _this._caps.textureAnisotropicFilterExtension = null;
  97331. _this._caps.maxAnisotropy = 0;
  97332. _this._caps.uintIndices = false;
  97333. _this._caps.fragmentDepthSupported = false;
  97334. _this._caps.highPrecisionShaderSupported = true;
  97335. _this._caps.colorBufferFloat = false;
  97336. _this._caps.textureFloat = false;
  97337. _this._caps.textureFloatLinearFiltering = false;
  97338. _this._caps.textureFloatRender = false;
  97339. _this._caps.textureHalfFloat = false;
  97340. _this._caps.textureHalfFloatLinearFiltering = false;
  97341. _this._caps.textureHalfFloatRender = false;
  97342. _this._caps.textureLOD = false;
  97343. _this._caps.drawBuffersExtension = false;
  97344. _this._caps.depthTextureExtension = false;
  97345. _this._caps.vertexArrayObject = false;
  97346. _this._caps.instancedArrays = false;
  97347. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97348. // Wrappers
  97349. if (typeof URL === "undefined") {
  97350. URL = {
  97351. createObjectURL: function () { },
  97352. revokeObjectURL: function () { }
  97353. };
  97354. }
  97355. if (typeof Blob === "undefined") {
  97356. Blob = function () { };
  97357. }
  97358. return _this;
  97359. }
  97360. NullEngine.prototype.isDeterministicLockStep = function () {
  97361. return this._options.deterministicLockstep;
  97362. };
  97363. NullEngine.prototype.getLockstepMaxSteps = function () {
  97364. return this._options.lockstepMaxSteps;
  97365. };
  97366. NullEngine.prototype.getHardwareScalingLevel = function () {
  97367. return 1.0;
  97368. };
  97369. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97370. return {
  97371. capacity: 0,
  97372. references: 1,
  97373. is32Bits: false
  97374. };
  97375. };
  97376. NullEngine.prototype.createIndexBuffer = function (indices) {
  97377. return {
  97378. capacity: 0,
  97379. references: 1,
  97380. is32Bits: false
  97381. };
  97382. };
  97383. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97384. if (stencil === void 0) { stencil = false; }
  97385. };
  97386. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97387. if (useScreen === void 0) { useScreen = false; }
  97388. if (!useScreen && this._currentRenderTarget) {
  97389. return this._currentRenderTarget.width;
  97390. }
  97391. return this._options.renderWidth;
  97392. };
  97393. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97394. if (useScreen === void 0) { useScreen = false; }
  97395. if (!useScreen && this._currentRenderTarget) {
  97396. return this._currentRenderTarget.height;
  97397. }
  97398. return this._options.renderHeight;
  97399. };
  97400. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97401. this._cachedViewport = viewport;
  97402. };
  97403. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97404. return {
  97405. transformFeedback: null,
  97406. __SPECTOR_rebuildProgram: null
  97407. };
  97408. };
  97409. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97410. return [];
  97411. };
  97412. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97413. return [];
  97414. };
  97415. NullEngine.prototype.bindSamplers = function (effect) {
  97416. this._currentEffect = null;
  97417. };
  97418. NullEngine.prototype.enableEffect = function (effect) {
  97419. this._currentEffect = effect;
  97420. if (effect.onBind) {
  97421. effect.onBind(effect);
  97422. }
  97423. effect.onBindObservable.notifyObservers(effect);
  97424. };
  97425. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97426. if (zOffset === void 0) { zOffset = 0; }
  97427. if (reverseSide === void 0) { reverseSide = false; }
  97428. };
  97429. NullEngine.prototype.setIntArray = function (uniform, array) {
  97430. };
  97431. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97432. };
  97433. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97434. };
  97435. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97436. };
  97437. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97438. };
  97439. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97440. };
  97441. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97442. };
  97443. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97444. };
  97445. NullEngine.prototype.setArray = function (uniform, array) {
  97446. };
  97447. NullEngine.prototype.setArray2 = function (uniform, array) {
  97448. };
  97449. NullEngine.prototype.setArray3 = function (uniform, array) {
  97450. };
  97451. NullEngine.prototype.setArray4 = function (uniform, array) {
  97452. };
  97453. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97454. };
  97455. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97456. };
  97457. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97458. };
  97459. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97460. };
  97461. NullEngine.prototype.setFloat = function (uniform, value) {
  97462. };
  97463. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97464. };
  97465. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97466. };
  97467. NullEngine.prototype.setBool = function (uniform, bool) {
  97468. };
  97469. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97470. };
  97471. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97472. };
  97473. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97474. };
  97475. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97476. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97477. if (this._alphaMode === mode) {
  97478. return;
  97479. }
  97480. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97481. if (!noDepthWriteChange) {
  97482. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97483. }
  97484. this._alphaMode = mode;
  97485. };
  97486. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97487. };
  97488. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97489. if (this.preventCacheWipeBetweenFrames) {
  97490. return;
  97491. }
  97492. this.resetTextureCache();
  97493. this._currentEffect = null;
  97494. if (bruteForce) {
  97495. this._currentProgram = null;
  97496. this._stencilState.reset();
  97497. this._depthCullingState.reset();
  97498. this._alphaState.reset();
  97499. }
  97500. this._cachedVertexBuffers = null;
  97501. this._cachedIndexBuffer = null;
  97502. this._cachedEffectForVertexBuffers = null;
  97503. };
  97504. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97505. };
  97506. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97507. };
  97508. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97509. };
  97510. NullEngine.prototype._createTexture = function () {
  97511. return {};
  97512. };
  97513. NullEngine.prototype._releaseTexture = function (texture) {
  97514. };
  97515. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97516. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97517. if (onLoad === void 0) { onLoad = null; }
  97518. if (onError === void 0) { onError = null; }
  97519. if (buffer === void 0) { buffer = null; }
  97520. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97521. var url = String(urlArg);
  97522. texture.url = url;
  97523. texture.generateMipMaps = !noMipmap;
  97524. texture.samplingMode = samplingMode;
  97525. texture.invertY = invertY;
  97526. texture.baseWidth = this._options.textureSize;
  97527. texture.baseHeight = this._options.textureSize;
  97528. texture.width = this._options.textureSize;
  97529. texture.height = this._options.textureSize;
  97530. if (format) {
  97531. texture.format = format;
  97532. }
  97533. texture.isReady = true;
  97534. if (onLoad) {
  97535. onLoad();
  97536. }
  97537. this._internalTexturesCache.push(texture);
  97538. return texture;
  97539. };
  97540. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97541. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97542. if (options !== undefined && typeof options === "object") {
  97543. fullOptions.generateMipMaps = options.generateMipMaps;
  97544. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97545. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97546. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97547. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97548. }
  97549. else {
  97550. fullOptions.generateMipMaps = options;
  97551. fullOptions.generateDepthBuffer = true;
  97552. fullOptions.generateStencilBuffer = false;
  97553. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97554. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97555. }
  97556. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97557. var width = size.width || size;
  97558. var height = size.height || size;
  97559. texture._depthStencilBuffer = {};
  97560. texture._framebuffer = {};
  97561. texture.baseWidth = width;
  97562. texture.baseHeight = height;
  97563. texture.width = width;
  97564. texture.height = height;
  97565. texture.isReady = true;
  97566. texture.samples = 1;
  97567. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97568. texture.samplingMode = fullOptions.samplingMode;
  97569. texture.type = fullOptions.type;
  97570. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97571. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97572. this._internalTexturesCache.push(texture);
  97573. return texture;
  97574. };
  97575. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97576. texture.samplingMode = samplingMode;
  97577. };
  97578. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97579. if (this._currentRenderTarget) {
  97580. this.unBindFramebuffer(this._currentRenderTarget);
  97581. }
  97582. this._currentRenderTarget = texture;
  97583. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97584. if (this._cachedViewport && !forceFullscreenViewport) {
  97585. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97586. }
  97587. };
  97588. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97589. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97590. this._currentRenderTarget = null;
  97591. if (onBeforeUnbind) {
  97592. if (texture._MSAAFramebuffer) {
  97593. this._currentFramebuffer = texture._framebuffer;
  97594. }
  97595. onBeforeUnbind();
  97596. }
  97597. this._currentFramebuffer = null;
  97598. };
  97599. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  97600. var vbo = {
  97601. capacity: 1,
  97602. references: 1,
  97603. is32Bits: false
  97604. };
  97605. return vbo;
  97606. };
  97607. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  97608. if (offset === void 0) { offset = 0; }
  97609. };
  97610. /**
  97611. * Updates a dynamic vertex buffer.
  97612. * @param vertexBuffer the vertex buffer to update
  97613. * @param data the data used to update the vertex buffer
  97614. * @param byteOffset the byte offset of the data (optional)
  97615. * @param byteLength the byte length of the data (optional)
  97616. */
  97617. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  97618. };
  97619. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  97620. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  97621. this._boundTexturesCache[this._activeChannel] = texture;
  97622. }
  97623. };
  97624. NullEngine.prototype._bindTexture = function (channel, texture) {
  97625. if (channel < 0) {
  97626. return;
  97627. }
  97628. this._bindTextureDirectly(0, texture);
  97629. };
  97630. NullEngine.prototype._releaseBuffer = function (buffer) {
  97631. buffer.references--;
  97632. if (buffer.references === 0) {
  97633. return true;
  97634. }
  97635. return false;
  97636. };
  97637. NullEngine.prototype.releaseEffects = function () {
  97638. };
  97639. return NullEngine;
  97640. }(BABYLON.Engine));
  97641. BABYLON.NullEngine = NullEngine;
  97642. })(BABYLON || (BABYLON = {}));
  97643. //# sourceMappingURL=babylon.nullEngine.js.map
  97644. var BABYLON;
  97645. (function (BABYLON) {
  97646. /**
  97647. * This class can be used to get instrumentation data from a Babylon engine
  97648. */
  97649. var EngineInstrumentation = /** @class */ (function () {
  97650. function EngineInstrumentation(engine) {
  97651. this.engine = engine;
  97652. this._captureGPUFrameTime = false;
  97653. this._gpuFrameTime = new BABYLON.PerfCounter();
  97654. this._captureShaderCompilationTime = false;
  97655. this._shaderCompilationTime = new BABYLON.PerfCounter();
  97656. // Observers
  97657. this._onBeginFrameObserver = null;
  97658. this._onEndFrameObserver = null;
  97659. this._onBeforeShaderCompilationObserver = null;
  97660. this._onAfterShaderCompilationObserver = null;
  97661. }
  97662. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  97663. // Properties
  97664. /**
  97665. * Gets the perf counter used for GPU frame time
  97666. */
  97667. get: function () {
  97668. return this._gpuFrameTime;
  97669. },
  97670. enumerable: true,
  97671. configurable: true
  97672. });
  97673. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  97674. /**
  97675. * Gets the GPU frame time capture status
  97676. */
  97677. get: function () {
  97678. return this._captureGPUFrameTime;
  97679. },
  97680. /**
  97681. * Enable or disable the GPU frame time capture
  97682. */
  97683. set: function (value) {
  97684. var _this = this;
  97685. if (value === this._captureGPUFrameTime) {
  97686. return;
  97687. }
  97688. this._captureGPUFrameTime = value;
  97689. if (value) {
  97690. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  97691. if (!_this._gpuFrameTimeToken) {
  97692. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  97693. }
  97694. });
  97695. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  97696. if (!_this._gpuFrameTimeToken) {
  97697. return;
  97698. }
  97699. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  97700. if (time > -1) {
  97701. _this._gpuFrameTimeToken = null;
  97702. _this._gpuFrameTime.fetchNewFrame();
  97703. _this._gpuFrameTime.addCount(time, true);
  97704. }
  97705. });
  97706. }
  97707. else {
  97708. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97709. this._onBeginFrameObserver = null;
  97710. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97711. this._onEndFrameObserver = null;
  97712. }
  97713. },
  97714. enumerable: true,
  97715. configurable: true
  97716. });
  97717. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  97718. /**
  97719. * Gets the perf counter used for shader compilation time
  97720. */
  97721. get: function () {
  97722. return this._shaderCompilationTime;
  97723. },
  97724. enumerable: true,
  97725. configurable: true
  97726. });
  97727. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  97728. /**
  97729. * Gets the shader compilation time capture status
  97730. */
  97731. get: function () {
  97732. return this._captureShaderCompilationTime;
  97733. },
  97734. /**
  97735. * Enable or disable the shader compilation time capture
  97736. */
  97737. set: function (value) {
  97738. var _this = this;
  97739. if (value === this._captureShaderCompilationTime) {
  97740. return;
  97741. }
  97742. this._captureShaderCompilationTime = value;
  97743. if (value) {
  97744. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  97745. _this._shaderCompilationTime.fetchNewFrame();
  97746. _this._shaderCompilationTime.beginMonitoring();
  97747. });
  97748. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  97749. _this._shaderCompilationTime.endMonitoring();
  97750. });
  97751. }
  97752. else {
  97753. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97754. this._onBeforeShaderCompilationObserver = null;
  97755. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97756. this._onAfterShaderCompilationObserver = null;
  97757. }
  97758. },
  97759. enumerable: true,
  97760. configurable: true
  97761. });
  97762. EngineInstrumentation.prototype.dispose = function () {
  97763. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97764. this._onBeginFrameObserver = null;
  97765. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97766. this._onEndFrameObserver = null;
  97767. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97768. this._onBeforeShaderCompilationObserver = null;
  97769. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97770. this._onAfterShaderCompilationObserver = null;
  97771. this.engine = null;
  97772. };
  97773. return EngineInstrumentation;
  97774. }());
  97775. BABYLON.EngineInstrumentation = EngineInstrumentation;
  97776. })(BABYLON || (BABYLON = {}));
  97777. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  97778. var BABYLON;
  97779. (function (BABYLON) {
  97780. /**
  97781. * This class can be used to get instrumentation data from a Babylon engine
  97782. */
  97783. var SceneInstrumentation = /** @class */ (function () {
  97784. function SceneInstrumentation(scene) {
  97785. var _this = this;
  97786. this.scene = scene;
  97787. this._captureActiveMeshesEvaluationTime = false;
  97788. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  97789. this._captureRenderTargetsRenderTime = false;
  97790. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  97791. this._captureFrameTime = false;
  97792. this._frameTime = new BABYLON.PerfCounter();
  97793. this._captureRenderTime = false;
  97794. this._renderTime = new BABYLON.PerfCounter();
  97795. this._captureInterFrameTime = false;
  97796. this._interFrameTime = new BABYLON.PerfCounter();
  97797. this._captureParticlesRenderTime = false;
  97798. this._particlesRenderTime = new BABYLON.PerfCounter();
  97799. this._captureSpritesRenderTime = false;
  97800. this._spritesRenderTime = new BABYLON.PerfCounter();
  97801. this._capturePhysicsTime = false;
  97802. this._physicsTime = new BABYLON.PerfCounter();
  97803. this._captureAnimationsTime = false;
  97804. this._animationsTime = new BABYLON.PerfCounter();
  97805. // Observers
  97806. this._onBeforeActiveMeshesEvaluationObserver = null;
  97807. this._onAfterActiveMeshesEvaluationObserver = null;
  97808. this._onBeforeRenderTargetsRenderObserver = null;
  97809. this._onAfterRenderTargetsRenderObserver = null;
  97810. this._onAfterRenderObserver = null;
  97811. this._onBeforeDrawPhaseObserver = null;
  97812. this._onAfterDrawPhaseObserver = null;
  97813. this._onBeforeAnimationsObserver = null;
  97814. this._onBeforeParticlesRenderingObserver = null;
  97815. this._onAfterParticlesRenderingObserver = null;
  97816. this._onBeforeSpritesRenderingObserver = null;
  97817. this._onAfterSpritesRenderingObserver = null;
  97818. this._onBeforePhysicsObserver = null;
  97819. this._onAfterPhysicsObserver = null;
  97820. this._onAfterAnimationsObserver = null;
  97821. // Before render
  97822. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  97823. if (_this._captureActiveMeshesEvaluationTime) {
  97824. _this._activeMeshesEvaluationTime.fetchNewFrame();
  97825. }
  97826. if (_this._captureRenderTargetsRenderTime) {
  97827. _this._renderTargetsRenderTime.fetchNewFrame();
  97828. }
  97829. if (_this._captureFrameTime) {
  97830. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  97831. _this._frameTime.beginMonitoring();
  97832. }
  97833. if (_this._captureInterFrameTime) {
  97834. _this._interFrameTime.endMonitoring();
  97835. }
  97836. if (_this._captureParticlesRenderTime) {
  97837. _this._particlesRenderTime.fetchNewFrame();
  97838. }
  97839. if (_this._captureSpritesRenderTime) {
  97840. _this._spritesRenderTime.fetchNewFrame();
  97841. }
  97842. if (_this._captureAnimationsTime) {
  97843. _this._animationsTime.beginMonitoring();
  97844. }
  97845. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  97846. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  97847. });
  97848. // After render
  97849. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  97850. if (_this._captureFrameTime) {
  97851. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  97852. _this._frameTime.endMonitoring();
  97853. }
  97854. if (_this._captureRenderTime) {
  97855. _this._renderTime.endMonitoring(false);
  97856. }
  97857. if (_this._captureInterFrameTime) {
  97858. _this._interFrameTime.beginMonitoring();
  97859. }
  97860. });
  97861. }
  97862. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  97863. // Properties
  97864. /**
  97865. * Gets the perf counter used for active meshes evaluation time
  97866. */
  97867. get: function () {
  97868. return this._activeMeshesEvaluationTime;
  97869. },
  97870. enumerable: true,
  97871. configurable: true
  97872. });
  97873. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  97874. /**
  97875. * Gets the active meshes evaluation time capture status
  97876. */
  97877. get: function () {
  97878. return this._captureActiveMeshesEvaluationTime;
  97879. },
  97880. /**
  97881. * Enable or disable the active meshes evaluation time capture
  97882. */
  97883. set: function (value) {
  97884. var _this = this;
  97885. if (value === this._captureActiveMeshesEvaluationTime) {
  97886. return;
  97887. }
  97888. this._captureActiveMeshesEvaluationTime = value;
  97889. if (value) {
  97890. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  97891. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  97892. _this._activeMeshesEvaluationTime.beginMonitoring();
  97893. });
  97894. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  97895. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  97896. _this._activeMeshesEvaluationTime.endMonitoring();
  97897. });
  97898. }
  97899. else {
  97900. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  97901. this._onBeforeActiveMeshesEvaluationObserver = null;
  97902. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  97903. this._onAfterActiveMeshesEvaluationObserver = null;
  97904. }
  97905. },
  97906. enumerable: true,
  97907. configurable: true
  97908. });
  97909. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  97910. /**
  97911. * Gets the perf counter used for render targets render time
  97912. */
  97913. get: function () {
  97914. return this._renderTargetsRenderTime;
  97915. },
  97916. enumerable: true,
  97917. configurable: true
  97918. });
  97919. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  97920. /**
  97921. * Gets the render targets render time capture status
  97922. */
  97923. get: function () {
  97924. return this._captureRenderTargetsRenderTime;
  97925. },
  97926. /**
  97927. * Enable or disable the render targets render time capture
  97928. */
  97929. set: function (value) {
  97930. var _this = this;
  97931. if (value === this._captureRenderTargetsRenderTime) {
  97932. return;
  97933. }
  97934. this._captureRenderTargetsRenderTime = value;
  97935. if (value) {
  97936. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  97937. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  97938. _this._renderTargetsRenderTime.beginMonitoring();
  97939. });
  97940. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  97941. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  97942. _this._renderTargetsRenderTime.endMonitoring(false);
  97943. });
  97944. }
  97945. else {
  97946. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  97947. this._onBeforeRenderTargetsRenderObserver = null;
  97948. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  97949. this._onAfterRenderTargetsRenderObserver = null;
  97950. }
  97951. },
  97952. enumerable: true,
  97953. configurable: true
  97954. });
  97955. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  97956. /**
  97957. * Gets the perf counter used for particles render time
  97958. */
  97959. get: function () {
  97960. return this._particlesRenderTime;
  97961. },
  97962. enumerable: true,
  97963. configurable: true
  97964. });
  97965. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  97966. /**
  97967. * Gets the particles render time capture status
  97968. */
  97969. get: function () {
  97970. return this._captureParticlesRenderTime;
  97971. },
  97972. /**
  97973. * Enable or disable the particles render time capture
  97974. */
  97975. set: function (value) {
  97976. var _this = this;
  97977. if (value === this._captureParticlesRenderTime) {
  97978. return;
  97979. }
  97980. this._captureParticlesRenderTime = value;
  97981. if (value) {
  97982. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  97983. BABYLON.Tools.StartPerformanceCounter("Particles");
  97984. _this._particlesRenderTime.beginMonitoring();
  97985. });
  97986. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  97987. BABYLON.Tools.EndPerformanceCounter("Particles");
  97988. _this._particlesRenderTime.endMonitoring(false);
  97989. });
  97990. }
  97991. else {
  97992. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  97993. this._onBeforeParticlesRenderingObserver = null;
  97994. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  97995. this._onAfterParticlesRenderingObserver = null;
  97996. }
  97997. },
  97998. enumerable: true,
  97999. configurable: true
  98000. });
  98001. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  98002. /**
  98003. * Gets the perf counter used for sprites render time
  98004. */
  98005. get: function () {
  98006. return this._spritesRenderTime;
  98007. },
  98008. enumerable: true,
  98009. configurable: true
  98010. });
  98011. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  98012. /**
  98013. * Gets the sprites render time capture status
  98014. */
  98015. get: function () {
  98016. return this._captureSpritesRenderTime;
  98017. },
  98018. /**
  98019. * Enable or disable the sprites render time capture
  98020. */
  98021. set: function (value) {
  98022. var _this = this;
  98023. if (value === this._captureSpritesRenderTime) {
  98024. return;
  98025. }
  98026. this._captureSpritesRenderTime = value;
  98027. if (value) {
  98028. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  98029. BABYLON.Tools.StartPerformanceCounter("Sprites");
  98030. _this._spritesRenderTime.beginMonitoring();
  98031. });
  98032. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  98033. BABYLON.Tools.EndPerformanceCounter("Sprites");
  98034. _this._spritesRenderTime.endMonitoring(false);
  98035. });
  98036. }
  98037. else {
  98038. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98039. this._onBeforeSpritesRenderingObserver = null;
  98040. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98041. this._onAfterSpritesRenderingObserver = null;
  98042. }
  98043. },
  98044. enumerable: true,
  98045. configurable: true
  98046. });
  98047. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  98048. /**
  98049. * Gets the perf counter used for physics time
  98050. */
  98051. get: function () {
  98052. return this._physicsTime;
  98053. },
  98054. enumerable: true,
  98055. configurable: true
  98056. });
  98057. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  98058. /**
  98059. * Gets the physics time capture status
  98060. */
  98061. get: function () {
  98062. return this._capturePhysicsTime;
  98063. },
  98064. /**
  98065. * Enable or disable the physics time capture
  98066. */
  98067. set: function (value) {
  98068. var _this = this;
  98069. if (value === this._capturePhysicsTime) {
  98070. return;
  98071. }
  98072. this._capturePhysicsTime = value;
  98073. if (value) {
  98074. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  98075. BABYLON.Tools.StartPerformanceCounter("Physics");
  98076. _this._physicsTime.beginMonitoring();
  98077. });
  98078. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  98079. BABYLON.Tools.EndPerformanceCounter("Physics");
  98080. _this._physicsTime.endMonitoring();
  98081. });
  98082. }
  98083. else {
  98084. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98085. this._onBeforePhysicsObserver = null;
  98086. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98087. this._onAfterPhysicsObserver = null;
  98088. }
  98089. },
  98090. enumerable: true,
  98091. configurable: true
  98092. });
  98093. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  98094. /**
  98095. * Gets the perf counter used for animations time
  98096. */
  98097. get: function () {
  98098. return this._animationsTime;
  98099. },
  98100. enumerable: true,
  98101. configurable: true
  98102. });
  98103. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  98104. /**
  98105. * Gets the animations time capture status
  98106. */
  98107. get: function () {
  98108. return this._captureAnimationsTime;
  98109. },
  98110. /**
  98111. * Enable or disable the animations time capture
  98112. */
  98113. set: function (value) {
  98114. var _this = this;
  98115. if (value === this._captureAnimationsTime) {
  98116. return;
  98117. }
  98118. this._captureAnimationsTime = value;
  98119. if (value) {
  98120. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98121. _this._animationsTime.endMonitoring();
  98122. });
  98123. }
  98124. else {
  98125. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98126. this._onAfterAnimationsObserver = null;
  98127. }
  98128. },
  98129. enumerable: true,
  98130. configurable: true
  98131. });
  98132. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98133. /**
  98134. * Gets the perf counter used for frame time capture
  98135. */
  98136. get: function () {
  98137. return this._frameTime;
  98138. },
  98139. enumerable: true,
  98140. configurable: true
  98141. });
  98142. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98143. /**
  98144. * Gets the frame time capture status
  98145. */
  98146. get: function () {
  98147. return this._captureFrameTime;
  98148. },
  98149. /**
  98150. * Enable or disable the frame time capture
  98151. */
  98152. set: function (value) {
  98153. this._captureFrameTime = value;
  98154. },
  98155. enumerable: true,
  98156. configurable: true
  98157. });
  98158. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98159. /**
  98160. * Gets the perf counter used for inter-frames time capture
  98161. */
  98162. get: function () {
  98163. return this._interFrameTime;
  98164. },
  98165. enumerable: true,
  98166. configurable: true
  98167. });
  98168. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98169. /**
  98170. * Gets the inter-frames time capture status
  98171. */
  98172. get: function () {
  98173. return this._captureInterFrameTime;
  98174. },
  98175. /**
  98176. * Enable or disable the inter-frames time capture
  98177. */
  98178. set: function (value) {
  98179. this._captureInterFrameTime = value;
  98180. },
  98181. enumerable: true,
  98182. configurable: true
  98183. });
  98184. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98185. /**
  98186. * Gets the perf counter used for render time capture
  98187. */
  98188. get: function () {
  98189. return this._renderTime;
  98190. },
  98191. enumerable: true,
  98192. configurable: true
  98193. });
  98194. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98195. /**
  98196. * Gets the render time capture status
  98197. */
  98198. get: function () {
  98199. return this._captureRenderTime;
  98200. },
  98201. /**
  98202. * Enable or disable the render time capture
  98203. */
  98204. set: function (value) {
  98205. var _this = this;
  98206. if (value === this._captureRenderTime) {
  98207. return;
  98208. }
  98209. this._captureRenderTime = value;
  98210. if (value) {
  98211. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98212. _this._renderTime.beginMonitoring();
  98213. BABYLON.Tools.StartPerformanceCounter("Main render");
  98214. });
  98215. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98216. _this._renderTime.endMonitoring(false);
  98217. BABYLON.Tools.EndPerformanceCounter("Main render");
  98218. });
  98219. }
  98220. else {
  98221. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98222. this._onBeforeDrawPhaseObserver = null;
  98223. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98224. this._onAfterDrawPhaseObserver = null;
  98225. }
  98226. },
  98227. enumerable: true,
  98228. configurable: true
  98229. });
  98230. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98231. /**
  98232. * Gets the perf counter used for draw calls
  98233. */
  98234. get: function () {
  98235. return this.scene.getEngine()._drawCalls;
  98236. },
  98237. enumerable: true,
  98238. configurable: true
  98239. });
  98240. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98241. /**
  98242. * Gets the perf counter used for texture collisions
  98243. */
  98244. get: function () {
  98245. return this.scene.getEngine()._textureCollisions;
  98246. },
  98247. enumerable: true,
  98248. configurable: true
  98249. });
  98250. SceneInstrumentation.prototype.dispose = function () {
  98251. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98252. this._onAfterRenderObserver = null;
  98253. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98254. this._onBeforeActiveMeshesEvaluationObserver = null;
  98255. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98256. this._onAfterActiveMeshesEvaluationObserver = null;
  98257. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98258. this._onBeforeRenderTargetsRenderObserver = null;
  98259. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98260. this._onAfterRenderTargetsRenderObserver = null;
  98261. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98262. this._onBeforeAnimationsObserver = null;
  98263. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98264. this._onBeforeParticlesRenderingObserver = null;
  98265. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98266. this._onAfterParticlesRenderingObserver = null;
  98267. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98268. this._onBeforeSpritesRenderingObserver = null;
  98269. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98270. this._onAfterSpritesRenderingObserver = null;
  98271. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98272. this._onBeforeDrawPhaseObserver = null;
  98273. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98274. this._onAfterDrawPhaseObserver = null;
  98275. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98276. this._onBeforePhysicsObserver = null;
  98277. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98278. this._onAfterPhysicsObserver = null;
  98279. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98280. this._onAfterAnimationsObserver = null;
  98281. this.scene = null;
  98282. };
  98283. return SceneInstrumentation;
  98284. }());
  98285. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98286. })(BABYLON || (BABYLON = {}));
  98287. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98288. var BABYLON;
  98289. (function (BABYLON) {
  98290. /**
  98291. * @hidden
  98292. **/
  98293. var _TimeToken = /** @class */ (function () {
  98294. function _TimeToken() {
  98295. this._timeElapsedQueryEnded = false;
  98296. }
  98297. return _TimeToken;
  98298. }());
  98299. BABYLON._TimeToken = _TimeToken;
  98300. })(BABYLON || (BABYLON = {}));
  98301. //# sourceMappingURL=babylon.timeToken.js.map
  98302. var BABYLON;
  98303. (function (BABYLON) {
  98304. /**
  98305. * Background material defines definition.
  98306. * @hidden Mainly internal Use
  98307. */
  98308. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98309. __extends(BackgroundMaterialDefines, _super);
  98310. /**
  98311. * Constructor of the defines.
  98312. */
  98313. function BackgroundMaterialDefines() {
  98314. var _this = _super.call(this) || this;
  98315. /**
  98316. * True if the diffuse texture is in use.
  98317. */
  98318. _this.DIFFUSE = false;
  98319. /**
  98320. * The direct UV channel to use.
  98321. */
  98322. _this.DIFFUSEDIRECTUV = 0;
  98323. /**
  98324. * True if the diffuse texture is in gamma space.
  98325. */
  98326. _this.GAMMADIFFUSE = false;
  98327. /**
  98328. * True if the diffuse texture has opacity in the alpha channel.
  98329. */
  98330. _this.DIFFUSEHASALPHA = false;
  98331. /**
  98332. * True if you want the material to fade to transparent at grazing angle.
  98333. */
  98334. _this.OPACITYFRESNEL = false;
  98335. /**
  98336. * True if an extra blur needs to be added in the reflection.
  98337. */
  98338. _this.REFLECTIONBLUR = false;
  98339. /**
  98340. * True if you want the material to fade to reflection at grazing angle.
  98341. */
  98342. _this.REFLECTIONFRESNEL = false;
  98343. /**
  98344. * True if you want the material to falloff as far as you move away from the scene center.
  98345. */
  98346. _this.REFLECTIONFALLOFF = false;
  98347. /**
  98348. * False if the current Webgl implementation does not support the texture lod extension.
  98349. */
  98350. _this.TEXTURELODSUPPORT = false;
  98351. /**
  98352. * True to ensure the data are premultiplied.
  98353. */
  98354. _this.PREMULTIPLYALPHA = false;
  98355. /**
  98356. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98357. */
  98358. _this.USERGBCOLOR = false;
  98359. /**
  98360. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98361. * stays aligned with the desired configuration.
  98362. */
  98363. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98364. /**
  98365. * True to add noise in order to reduce the banding effect.
  98366. */
  98367. _this.NOISE = false;
  98368. /**
  98369. * is the reflection texture in BGR color scheme?
  98370. * Mainly used to solve a bug in ios10 video tag
  98371. */
  98372. _this.REFLECTIONBGR = false;
  98373. _this.IMAGEPROCESSING = false;
  98374. _this.VIGNETTE = false;
  98375. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98376. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98377. _this.TONEMAPPING = false;
  98378. _this.CONTRAST = false;
  98379. _this.COLORCURVES = false;
  98380. _this.COLORGRADING = false;
  98381. _this.COLORGRADING3D = false;
  98382. _this.SAMPLER3DGREENDEPTH = false;
  98383. _this.SAMPLER3DBGRMAP = false;
  98384. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98385. _this.EXPOSURE = false;
  98386. // Reflection.
  98387. _this.REFLECTION = false;
  98388. _this.REFLECTIONMAP_3D = false;
  98389. _this.REFLECTIONMAP_SPHERICAL = false;
  98390. _this.REFLECTIONMAP_PLANAR = false;
  98391. _this.REFLECTIONMAP_CUBIC = false;
  98392. _this.REFLECTIONMAP_PROJECTION = false;
  98393. _this.REFLECTIONMAP_SKYBOX = false;
  98394. _this.REFLECTIONMAP_EXPLICIT = false;
  98395. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98396. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98397. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98398. _this.INVERTCUBICMAP = false;
  98399. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98400. _this.LODINREFLECTIONALPHA = false;
  98401. _this.GAMMAREFLECTION = false;
  98402. _this.RGBDREFLECTION = false;
  98403. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98404. // Default BJS.
  98405. _this.MAINUV1 = false;
  98406. _this.MAINUV2 = false;
  98407. _this.UV1 = false;
  98408. _this.UV2 = false;
  98409. _this.CLIPPLANE = false;
  98410. _this.POINTSIZE = false;
  98411. _this.FOG = false;
  98412. _this.NORMAL = false;
  98413. _this.NUM_BONE_INFLUENCERS = 0;
  98414. _this.BonesPerMesh = 0;
  98415. _this.INSTANCES = false;
  98416. _this.SHADOWFLOAT = false;
  98417. _this.rebuild();
  98418. return _this;
  98419. }
  98420. return BackgroundMaterialDefines;
  98421. }(BABYLON.MaterialDefines));
  98422. /**
  98423. * Background material used to create an efficient environement around your scene.
  98424. */
  98425. var BackgroundMaterial = /** @class */ (function (_super) {
  98426. __extends(BackgroundMaterial, _super);
  98427. /**
  98428. * Instantiates a Background Material in the given scene
  98429. * @param name The friendly name of the material
  98430. * @param scene The scene to add the material to
  98431. */
  98432. function BackgroundMaterial(name, scene) {
  98433. var _this = _super.call(this, name, scene) || this;
  98434. /**
  98435. * Key light Color (multiply against the environement texture)
  98436. */
  98437. _this.primaryColor = BABYLON.Color3.White();
  98438. _this._primaryColorShadowLevel = 0;
  98439. _this._primaryColorHighlightLevel = 0;
  98440. /**
  98441. * Reflection Texture used in the material.
  98442. * Should be author in a specific way for the best result (refer to the documentation).
  98443. */
  98444. _this.reflectionTexture = null;
  98445. /**
  98446. * Reflection Texture level of blur.
  98447. *
  98448. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98449. * texture twice.
  98450. */
  98451. _this.reflectionBlur = 0;
  98452. /**
  98453. * Diffuse Texture used in the material.
  98454. * Should be author in a specific way for the best result (refer to the documentation).
  98455. */
  98456. _this.diffuseTexture = null;
  98457. _this._shadowLights = null;
  98458. /**
  98459. * Specify the list of lights casting shadow on the material.
  98460. * All scene shadow lights will be included if null.
  98461. */
  98462. _this.shadowLights = null;
  98463. /**
  98464. * Helps adjusting the shadow to a softer level if required.
  98465. * 0 means black shadows and 1 means no shadows.
  98466. */
  98467. _this.shadowLevel = 0;
  98468. /**
  98469. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98470. * It is usually zero but might be interesting to modify according to your setup.
  98471. */
  98472. _this.sceneCenter = BABYLON.Vector3.Zero();
  98473. /**
  98474. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98475. * This helps ensuring a nice transition when the camera goes under the ground.
  98476. */
  98477. _this.opacityFresnel = true;
  98478. /**
  98479. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98480. * This helps adding a mirror texture on the ground.
  98481. */
  98482. _this.reflectionFresnel = false;
  98483. /**
  98484. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98485. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98486. */
  98487. _this.reflectionFalloffDistance = 0.0;
  98488. /**
  98489. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98490. */
  98491. _this.reflectionAmount = 1.0;
  98492. /**
  98493. * This specifies the weight of the reflection at grazing angle.
  98494. */
  98495. _this.reflectionReflectance0 = 0.05;
  98496. /**
  98497. * This specifies the weight of the reflection at a perpendicular point of view.
  98498. */
  98499. _this.reflectionReflectance90 = 0.5;
  98500. /**
  98501. * Helps to directly use the maps channels instead of their level.
  98502. */
  98503. _this.useRGBColor = true;
  98504. /**
  98505. * This helps reducing the banding effect that could occur on the background.
  98506. */
  98507. _this.enableNoise = false;
  98508. _this._fovMultiplier = 1.0;
  98509. /**
  98510. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98511. */
  98512. _this.useEquirectangularFOV = false;
  98513. _this._maxSimultaneousLights = 4;
  98514. /**
  98515. * Number of Simultaneous lights allowed on the material.
  98516. */
  98517. _this.maxSimultaneousLights = 4;
  98518. /**
  98519. * Keep track of the image processing observer to allow dispose and replace.
  98520. */
  98521. _this._imageProcessingObserver = null;
  98522. /**
  98523. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98524. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98525. */
  98526. _this.switchToBGR = false;
  98527. // Temp values kept as cache in the material.
  98528. _this._renderTargets = new BABYLON.SmartArray(16);
  98529. _this._reflectionControls = BABYLON.Vector4.Zero();
  98530. _this._white = BABYLON.Color3.White();
  98531. _this._primaryShadowColor = BABYLON.Color3.Black();
  98532. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98533. // Setup the default processing configuration to the scene.
  98534. _this._attachImageProcessingConfiguration(null);
  98535. _this.getRenderTargetTextures = function () {
  98536. _this._renderTargets.reset();
  98537. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98538. _this._renderTargets.push(_this._diffuseTexture);
  98539. }
  98540. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98541. _this._renderTargets.push(_this._reflectionTexture);
  98542. }
  98543. return _this._renderTargets;
  98544. };
  98545. return _this;
  98546. }
  98547. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  98548. /**
  98549. * Experimental Internal Use Only.
  98550. *
  98551. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  98552. * This acts as a helper to set the primary color to a more "human friendly" value.
  98553. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  98554. * output color as close as possible from the chosen value.
  98555. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  98556. * part of lighting setup.)
  98557. */
  98558. get: function () {
  98559. return this.__perceptualColor;
  98560. },
  98561. set: function (value) {
  98562. this.__perceptualColor = value;
  98563. this._computePrimaryColorFromPerceptualColor();
  98564. this._markAllSubMeshesAsLightsDirty();
  98565. },
  98566. enumerable: true,
  98567. configurable: true
  98568. });
  98569. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  98570. /**
  98571. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  98572. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  98573. */
  98574. get: function () {
  98575. return this._primaryColorShadowLevel;
  98576. },
  98577. set: function (value) {
  98578. this._primaryColorShadowLevel = value;
  98579. this._computePrimaryColors();
  98580. this._markAllSubMeshesAsLightsDirty();
  98581. },
  98582. enumerable: true,
  98583. configurable: true
  98584. });
  98585. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  98586. /**
  98587. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  98588. * The primary color is used at the level chosen to define what the white area would look.
  98589. */
  98590. get: function () {
  98591. return this._primaryColorHighlightLevel;
  98592. },
  98593. set: function (value) {
  98594. this._primaryColorHighlightLevel = value;
  98595. this._computePrimaryColors();
  98596. this._markAllSubMeshesAsLightsDirty();
  98597. },
  98598. enumerable: true,
  98599. configurable: true
  98600. });
  98601. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  98602. /**
  98603. * Sets the reflection reflectance fresnel values according to the default standard
  98604. * empirically know to work well :-)
  98605. */
  98606. set: function (value) {
  98607. var reflectionWeight = value;
  98608. if (reflectionWeight < 0.5) {
  98609. reflectionWeight = reflectionWeight * 2.0;
  98610. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  98611. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  98612. }
  98613. else {
  98614. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  98615. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  98616. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  98617. }
  98618. },
  98619. enumerable: true,
  98620. configurable: true
  98621. });
  98622. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  98623. /**
  98624. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98625. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  98626. * Recommended to be keep at 1.0 except for special cases.
  98627. */
  98628. get: function () {
  98629. return this._fovMultiplier;
  98630. },
  98631. set: function (value) {
  98632. if (isNaN(value)) {
  98633. value = 1.0;
  98634. }
  98635. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  98636. },
  98637. enumerable: true,
  98638. configurable: true
  98639. });
  98640. /**
  98641. * Attaches a new image processing configuration to the PBR Material.
  98642. * @param configuration (if null the scene configuration will be use)
  98643. */
  98644. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  98645. var _this = this;
  98646. if (configuration === this._imageProcessingConfiguration) {
  98647. return;
  98648. }
  98649. // Detaches observer.
  98650. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98651. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98652. }
  98653. // Pick the scene configuration if needed.
  98654. if (!configuration) {
  98655. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  98656. }
  98657. else {
  98658. this._imageProcessingConfiguration = configuration;
  98659. }
  98660. // Attaches observer.
  98661. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  98662. _this._computePrimaryColorFromPerceptualColor();
  98663. _this._markAllSubMeshesAsImageProcessingDirty();
  98664. });
  98665. };
  98666. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  98667. /**
  98668. * Gets the image processing configuration used either in this material.
  98669. */
  98670. get: function () {
  98671. return this._imageProcessingConfiguration;
  98672. },
  98673. /**
  98674. * Sets the Default image processing configuration used either in the this material.
  98675. *
  98676. * If sets to null, the scene one is in use.
  98677. */
  98678. set: function (value) {
  98679. this._attachImageProcessingConfiguration(value);
  98680. // Ensure the effect will be rebuilt.
  98681. this._markAllSubMeshesAsTexturesDirty();
  98682. },
  98683. enumerable: true,
  98684. configurable: true
  98685. });
  98686. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  98687. /**
  98688. * Gets wether the color curves effect is enabled.
  98689. */
  98690. get: function () {
  98691. return this.imageProcessingConfiguration.colorCurvesEnabled;
  98692. },
  98693. /**
  98694. * Sets wether the color curves effect is enabled.
  98695. */
  98696. set: function (value) {
  98697. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  98698. },
  98699. enumerable: true,
  98700. configurable: true
  98701. });
  98702. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  98703. /**
  98704. * Gets wether the color grading effect is enabled.
  98705. */
  98706. get: function () {
  98707. return this.imageProcessingConfiguration.colorGradingEnabled;
  98708. },
  98709. /**
  98710. * Gets wether the color grading effect is enabled.
  98711. */
  98712. set: function (value) {
  98713. this.imageProcessingConfiguration.colorGradingEnabled = value;
  98714. },
  98715. enumerable: true,
  98716. configurable: true
  98717. });
  98718. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  98719. /**
  98720. * Gets wether tonemapping is enabled or not.
  98721. */
  98722. get: function () {
  98723. return this._imageProcessingConfiguration.toneMappingEnabled;
  98724. },
  98725. /**
  98726. * Sets wether tonemapping is enabled or not
  98727. */
  98728. set: function (value) {
  98729. this._imageProcessingConfiguration.toneMappingEnabled = value;
  98730. },
  98731. enumerable: true,
  98732. configurable: true
  98733. });
  98734. ;
  98735. ;
  98736. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  98737. /**
  98738. * The camera exposure used on this material.
  98739. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98740. * This corresponds to a photographic exposure.
  98741. */
  98742. get: function () {
  98743. return this._imageProcessingConfiguration.exposure;
  98744. },
  98745. /**
  98746. * The camera exposure used on this material.
  98747. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98748. * This corresponds to a photographic exposure.
  98749. */
  98750. set: function (value) {
  98751. this._imageProcessingConfiguration.exposure = value;
  98752. },
  98753. enumerable: true,
  98754. configurable: true
  98755. });
  98756. ;
  98757. ;
  98758. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  98759. /**
  98760. * Gets The camera contrast used on this material.
  98761. */
  98762. get: function () {
  98763. return this._imageProcessingConfiguration.contrast;
  98764. },
  98765. /**
  98766. * Sets The camera contrast used on this material.
  98767. */
  98768. set: function (value) {
  98769. this._imageProcessingConfiguration.contrast = value;
  98770. },
  98771. enumerable: true,
  98772. configurable: true
  98773. });
  98774. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  98775. /**
  98776. * Gets the Color Grading 2D Lookup Texture.
  98777. */
  98778. get: function () {
  98779. return this._imageProcessingConfiguration.colorGradingTexture;
  98780. },
  98781. /**
  98782. * Sets the Color Grading 2D Lookup Texture.
  98783. */
  98784. set: function (value) {
  98785. this.imageProcessingConfiguration.colorGradingTexture = value;
  98786. },
  98787. enumerable: true,
  98788. configurable: true
  98789. });
  98790. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  98791. /**
  98792. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98793. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98794. * 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;
  98795. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98796. */
  98797. get: function () {
  98798. return this.imageProcessingConfiguration.colorCurves;
  98799. },
  98800. /**
  98801. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98802. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98803. * 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;
  98804. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98805. */
  98806. set: function (value) {
  98807. this.imageProcessingConfiguration.colorCurves = value;
  98808. },
  98809. enumerable: true,
  98810. configurable: true
  98811. });
  98812. /**
  98813. * The entire material has been created in order to prevent overdraw.
  98814. * @returns false
  98815. */
  98816. BackgroundMaterial.prototype.needAlphaTesting = function () {
  98817. return true;
  98818. };
  98819. /**
  98820. * The entire material has been created in order to prevent overdraw.
  98821. * @returns true if blending is enable
  98822. */
  98823. BackgroundMaterial.prototype.needAlphaBlending = function () {
  98824. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  98825. };
  98826. /**
  98827. * Checks wether the material is ready to be rendered for a given mesh.
  98828. * @param mesh The mesh to render
  98829. * @param subMesh The submesh to check against
  98830. * @param useInstances Specify wether or not the material is used with instances
  98831. * @returns true if all the dependencies are ready (Textures, Effects...)
  98832. */
  98833. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  98834. var _this = this;
  98835. if (useInstances === void 0) { useInstances = false; }
  98836. if (subMesh.effect && this.isFrozen) {
  98837. if (this._wasPreviouslyReady) {
  98838. return true;
  98839. }
  98840. }
  98841. if (!subMesh._materialDefines) {
  98842. subMesh._materialDefines = new BackgroundMaterialDefines();
  98843. }
  98844. var scene = this.getScene();
  98845. var defines = subMesh._materialDefines;
  98846. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  98847. if (defines._renderId === scene.getRenderId()) {
  98848. return true;
  98849. }
  98850. }
  98851. var engine = scene.getEngine();
  98852. // Lights
  98853. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  98854. defines._needNormals = true;
  98855. // Textures
  98856. if (defines._areTexturesDirty) {
  98857. defines._needUVs = false;
  98858. if (scene.texturesEnabled) {
  98859. if (scene.getEngine().getCaps().textureLOD) {
  98860. defines.TEXTURELODSUPPORT = true;
  98861. }
  98862. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98863. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  98864. return false;
  98865. }
  98866. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  98867. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  98868. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  98869. defines.OPACITYFRESNEL = this._opacityFresnel;
  98870. }
  98871. else {
  98872. defines.DIFFUSE = false;
  98873. defines.DIFFUSEHASALPHA = false;
  98874. defines.GAMMADIFFUSE = false;
  98875. defines.OPACITYFRESNEL = false;
  98876. }
  98877. var reflectionTexture = this._reflectionTexture;
  98878. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98879. if (!reflectionTexture.isReadyOrNotBlocking()) {
  98880. return false;
  98881. }
  98882. defines.REFLECTION = true;
  98883. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  98884. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  98885. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  98886. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  98887. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  98888. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  98889. defines.REFLECTIONBGR = this.switchToBGR;
  98890. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  98891. defines.INVERTCUBICMAP = true;
  98892. }
  98893. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  98894. switch (reflectionTexture.coordinatesMode) {
  98895. case BABYLON.Texture.EXPLICIT_MODE:
  98896. defines.REFLECTIONMAP_EXPLICIT = true;
  98897. break;
  98898. case BABYLON.Texture.PLANAR_MODE:
  98899. defines.REFLECTIONMAP_PLANAR = true;
  98900. break;
  98901. case BABYLON.Texture.PROJECTION_MODE:
  98902. defines.REFLECTIONMAP_PROJECTION = true;
  98903. break;
  98904. case BABYLON.Texture.SKYBOX_MODE:
  98905. defines.REFLECTIONMAP_SKYBOX = true;
  98906. break;
  98907. case BABYLON.Texture.SPHERICAL_MODE:
  98908. defines.REFLECTIONMAP_SPHERICAL = true;
  98909. break;
  98910. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  98911. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  98912. break;
  98913. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  98914. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  98915. break;
  98916. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  98917. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  98918. break;
  98919. case BABYLON.Texture.CUBIC_MODE:
  98920. case BABYLON.Texture.INVCUBIC_MODE:
  98921. default:
  98922. defines.REFLECTIONMAP_CUBIC = true;
  98923. break;
  98924. }
  98925. if (this.reflectionFresnel) {
  98926. defines.REFLECTIONFRESNEL = true;
  98927. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  98928. this._reflectionControls.x = this.reflectionAmount;
  98929. this._reflectionControls.y = this.reflectionReflectance0;
  98930. this._reflectionControls.z = this.reflectionReflectance90;
  98931. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  98932. }
  98933. else {
  98934. defines.REFLECTIONFRESNEL = false;
  98935. defines.REFLECTIONFALLOFF = false;
  98936. }
  98937. }
  98938. else {
  98939. defines.REFLECTION = false;
  98940. defines.REFLECTIONFRESNEL = false;
  98941. defines.REFLECTIONFALLOFF = false;
  98942. defines.REFLECTIONBLUR = false;
  98943. defines.REFLECTIONMAP_3D = false;
  98944. defines.REFLECTIONMAP_SPHERICAL = false;
  98945. defines.REFLECTIONMAP_PLANAR = false;
  98946. defines.REFLECTIONMAP_CUBIC = false;
  98947. defines.REFLECTIONMAP_PROJECTION = false;
  98948. defines.REFLECTIONMAP_SKYBOX = false;
  98949. defines.REFLECTIONMAP_EXPLICIT = false;
  98950. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98951. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98952. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98953. defines.INVERTCUBICMAP = false;
  98954. defines.REFLECTIONMAP_OPPOSITEZ = false;
  98955. defines.LODINREFLECTIONALPHA = false;
  98956. defines.GAMMAREFLECTION = false;
  98957. defines.RGBDREFLECTION = false;
  98958. }
  98959. }
  98960. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  98961. defines.USERGBCOLOR = this._useRGBColor;
  98962. defines.NOISE = this._enableNoise;
  98963. }
  98964. if (defines._areLightsDirty) {
  98965. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  98966. }
  98967. if (defines._areImageProcessingDirty) {
  98968. if (!this._imageProcessingConfiguration.isReady()) {
  98969. return false;
  98970. }
  98971. this._imageProcessingConfiguration.prepareDefines(defines);
  98972. }
  98973. // Misc.
  98974. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  98975. // Values that need to be evaluated on every frame
  98976. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  98977. // Attribs
  98978. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  98979. if (mesh) {
  98980. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98981. mesh.createNormals(true);
  98982. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  98983. }
  98984. }
  98985. }
  98986. // Get correct effect
  98987. if (defines.isDirty) {
  98988. defines.markAsProcessed();
  98989. scene.resetCachedMaterial();
  98990. // Fallbacks
  98991. var fallbacks = new BABYLON.EffectFallbacks();
  98992. if (defines.FOG) {
  98993. fallbacks.addFallback(0, "FOG");
  98994. }
  98995. if (defines.POINTSIZE) {
  98996. fallbacks.addFallback(1, "POINTSIZE");
  98997. }
  98998. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  98999. if (defines.NUM_BONE_INFLUENCERS > 0) {
  99000. fallbacks.addCPUSkinningFallback(0, mesh);
  99001. }
  99002. //Attributes
  99003. var attribs = [BABYLON.VertexBuffer.PositionKind];
  99004. if (defines.NORMAL) {
  99005. attribs.push(BABYLON.VertexBuffer.NormalKind);
  99006. }
  99007. if (defines.UV1) {
  99008. attribs.push(BABYLON.VertexBuffer.UVKind);
  99009. }
  99010. if (defines.UV2) {
  99011. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99012. }
  99013. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  99014. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  99015. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  99016. "vFogInfos", "vFogColor", "pointSize",
  99017. "vClipPlane", "mBones",
  99018. "vPrimaryColor", "vPrimaryColorShadow",
  99019. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  99020. "shadowLevel", "alpha",
  99021. "vBackgroundCenter", "vReflectionControl",
  99022. "vDiffuseInfos", "diffuseMatrix",
  99023. ];
  99024. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  99025. var uniformBuffers = ["Material", "Scene"];
  99026. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  99027. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  99028. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  99029. uniformsNames: uniforms,
  99030. uniformBuffersNames: uniformBuffers,
  99031. samplers: samplers,
  99032. defines: defines,
  99033. maxSimultaneousLights: this._maxSimultaneousLights
  99034. });
  99035. var onCompiled = function (effect) {
  99036. if (_this.onCompiled) {
  99037. _this.onCompiled(effect);
  99038. }
  99039. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  99040. };
  99041. var join = defines.toString();
  99042. subMesh.setEffect(scene.getEngine().createEffect("background", {
  99043. attributes: attribs,
  99044. uniformsNames: uniforms,
  99045. uniformBuffersNames: uniformBuffers,
  99046. samplers: samplers,
  99047. defines: join,
  99048. fallbacks: fallbacks,
  99049. onCompiled: onCompiled,
  99050. onError: this.onError,
  99051. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  99052. }, engine), defines);
  99053. this.buildUniformLayout();
  99054. }
  99055. if (!subMesh.effect || !subMesh.effect.isReady()) {
  99056. return false;
  99057. }
  99058. defines._renderId = scene.getRenderId();
  99059. this._wasPreviouslyReady = true;
  99060. return true;
  99061. };
  99062. /**
  99063. * Compute the primary color according to the chosen perceptual color.
  99064. */
  99065. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  99066. if (!this.__perceptualColor) {
  99067. return;
  99068. }
  99069. this._primaryColor.copyFrom(this.__perceptualColor);
  99070. // Revert gamma space.
  99071. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  99072. // Revert image processing configuration.
  99073. if (this._imageProcessingConfiguration) {
  99074. // Revert Exposure.
  99075. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  99076. }
  99077. this._computePrimaryColors();
  99078. };
  99079. /**
  99080. * Compute the highlights and shadow colors according to their chosen levels.
  99081. */
  99082. BackgroundMaterial.prototype._computePrimaryColors = function () {
  99083. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  99084. return;
  99085. }
  99086. // Find the highlight color based on the configuration.
  99087. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  99088. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  99089. // Find the shadow color based on the configuration.
  99090. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  99091. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  99092. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  99093. };
  99094. /**
  99095. * Build the uniform buffer used in the material.
  99096. */
  99097. BackgroundMaterial.prototype.buildUniformLayout = function () {
  99098. // Order is important !
  99099. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  99100. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  99101. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  99102. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  99103. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  99104. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  99105. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  99106. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  99107. this._uniformBuffer.addUniform("pointSize", 1);
  99108. this._uniformBuffer.addUniform("shadowLevel", 1);
  99109. this._uniformBuffer.addUniform("alpha", 1);
  99110. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99111. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99112. this._uniformBuffer.create();
  99113. };
  99114. /**
  99115. * Unbind the material.
  99116. */
  99117. BackgroundMaterial.prototype.unbind = function () {
  99118. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99119. this._uniformBuffer.setTexture("diffuseSampler", null);
  99120. }
  99121. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99122. this._uniformBuffer.setTexture("reflectionSampler", null);
  99123. }
  99124. _super.prototype.unbind.call(this);
  99125. };
  99126. /**
  99127. * Bind only the world matrix to the material.
  99128. * @param world The world matrix to bind.
  99129. */
  99130. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99131. this._activeEffect.setMatrix("world", world);
  99132. };
  99133. /**
  99134. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99135. * @param world The world matrix to bind.
  99136. * @param subMesh The submesh to bind for.
  99137. */
  99138. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99139. var scene = this.getScene();
  99140. var defines = subMesh._materialDefines;
  99141. if (!defines) {
  99142. return;
  99143. }
  99144. var effect = subMesh.effect;
  99145. if (!effect) {
  99146. return;
  99147. }
  99148. this._activeEffect = effect;
  99149. // Matrices
  99150. this.bindOnlyWorldMatrix(world);
  99151. // Bones
  99152. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99153. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99154. if (mustRebind) {
  99155. this._uniformBuffer.bindToEffect(effect, "Material");
  99156. this.bindViewProjection(effect);
  99157. var reflectionTexture = this._reflectionTexture;
  99158. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99159. // Texture uniforms
  99160. if (scene.texturesEnabled) {
  99161. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99162. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99163. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99164. }
  99165. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99166. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99167. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99168. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99169. }
  99170. }
  99171. if (this.shadowLevel > 0) {
  99172. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99173. }
  99174. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99175. // Point size
  99176. if (this.pointsCloud) {
  99177. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99178. }
  99179. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99180. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99181. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99182. }
  99183. else {
  99184. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99185. }
  99186. }
  99187. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99188. // Textures
  99189. if (scene.texturesEnabled) {
  99190. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99191. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99192. }
  99193. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99194. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99195. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99196. }
  99197. else if (!defines.REFLECTIONBLUR) {
  99198. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99199. }
  99200. else {
  99201. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99202. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99203. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99204. }
  99205. if (defines.REFLECTIONFRESNEL) {
  99206. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99207. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99208. }
  99209. }
  99210. }
  99211. // Clip plane
  99212. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99213. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99214. }
  99215. if (mustRebind || !this.isFrozen) {
  99216. if (scene.lightsEnabled) {
  99217. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99218. }
  99219. // View
  99220. this.bindView(effect);
  99221. // Fog
  99222. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99223. // image processing
  99224. this._imageProcessingConfiguration.bind(this._activeEffect);
  99225. }
  99226. this._uniformBuffer.update();
  99227. this._afterBind(mesh);
  99228. };
  99229. /**
  99230. * Dispose the material.
  99231. * @param forceDisposeEffect Force disposal of the associated effect.
  99232. * @param forceDisposeTextures Force disposal of the associated textures.
  99233. */
  99234. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99235. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99236. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99237. if (forceDisposeTextures) {
  99238. if (this.diffuseTexture) {
  99239. this.diffuseTexture.dispose();
  99240. }
  99241. if (this.reflectionTexture) {
  99242. this.reflectionTexture.dispose();
  99243. }
  99244. }
  99245. this._renderTargets.dispose();
  99246. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99247. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99248. }
  99249. _super.prototype.dispose.call(this, forceDisposeEffect);
  99250. };
  99251. /**
  99252. * Clones the material.
  99253. * @param name The cloned name.
  99254. * @returns The cloned material.
  99255. */
  99256. BackgroundMaterial.prototype.clone = function (name) {
  99257. var _this = this;
  99258. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99259. };
  99260. /**
  99261. * Serializes the current material to its JSON representation.
  99262. * @returns The JSON representation.
  99263. */
  99264. BackgroundMaterial.prototype.serialize = function () {
  99265. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99266. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99267. return serializationObject;
  99268. };
  99269. /**
  99270. * Gets the class name of the material
  99271. * @returns "BackgroundMaterial"
  99272. */
  99273. BackgroundMaterial.prototype.getClassName = function () {
  99274. return "BackgroundMaterial";
  99275. };
  99276. /**
  99277. * Parse a JSON input to create back a background material.
  99278. * @param source The JSON data to parse
  99279. * @param scene The scene to create the parsed material in
  99280. * @param rootUrl The root url of the assets the material depends upon
  99281. * @returns the instantiated BackgroundMaterial.
  99282. */
  99283. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99284. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99285. };
  99286. /**
  99287. * Standard reflectance value at parallel view angle.
  99288. */
  99289. BackgroundMaterial.StandardReflectance0 = 0.05;
  99290. /**
  99291. * Standard reflectance value at grazing angle.
  99292. */
  99293. BackgroundMaterial.StandardReflectance90 = 0.5;
  99294. __decorate([
  99295. BABYLON.serializeAsColor3()
  99296. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99297. __decorate([
  99298. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99299. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99300. __decorate([
  99301. BABYLON.serializeAsColor3()
  99302. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99303. __decorate([
  99304. BABYLON.serialize()
  99305. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99306. __decorate([
  99307. BABYLON.serialize()
  99308. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99309. __decorate([
  99310. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99311. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99312. __decorate([
  99313. BABYLON.serializeAsTexture()
  99314. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99315. __decorate([
  99316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99317. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99318. __decorate([
  99319. BABYLON.serialize()
  99320. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99321. __decorate([
  99322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99323. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99324. __decorate([
  99325. BABYLON.serializeAsTexture()
  99326. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99327. __decorate([
  99328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99329. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99330. __decorate([
  99331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99332. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99333. __decorate([
  99334. BABYLON.serialize()
  99335. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99336. __decorate([
  99337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99338. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99339. __decorate([
  99340. BABYLON.serializeAsVector3()
  99341. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99342. __decorate([
  99343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99344. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99345. __decorate([
  99346. BABYLON.serialize()
  99347. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99348. __decorate([
  99349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99350. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99351. __decorate([
  99352. BABYLON.serialize()
  99353. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99354. __decorate([
  99355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99356. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99357. __decorate([
  99358. BABYLON.serialize()
  99359. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99360. __decorate([
  99361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99362. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99363. __decorate([
  99364. BABYLON.serialize()
  99365. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99366. __decorate([
  99367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99368. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99369. __decorate([
  99370. BABYLON.serialize()
  99371. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99372. __decorate([
  99373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99374. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99375. __decorate([
  99376. BABYLON.serialize()
  99377. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99378. __decorate([
  99379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99380. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99381. __decorate([
  99382. BABYLON.serialize()
  99383. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99384. __decorate([
  99385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99386. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99387. __decorate([
  99388. BABYLON.serialize()
  99389. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99390. __decorate([
  99391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99392. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99393. __decorate([
  99394. BABYLON.serialize()
  99395. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99396. __decorate([
  99397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99398. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99399. __decorate([
  99400. BABYLON.serializeAsImageProcessingConfiguration()
  99401. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99402. return BackgroundMaterial;
  99403. }(BABYLON.PushMaterial));
  99404. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99405. })(BABYLON || (BABYLON = {}));
  99406. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99407. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99408. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99409. s = arguments[i];
  99410. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99411. t[p] = s[p];
  99412. }
  99413. return t;
  99414. };
  99415. var BABYLON;
  99416. (function (BABYLON) {
  99417. /**
  99418. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99419. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99420. * It also helps with the default setup of your imageProcessing configuration.
  99421. */
  99422. var EnvironmentHelper = /** @class */ (function () {
  99423. /**
  99424. * constructor
  99425. * @param options
  99426. * @param scene The scene to add the material to
  99427. */
  99428. function EnvironmentHelper(options, scene) {
  99429. var _this = this;
  99430. this._errorHandler = function (message, exception) {
  99431. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99432. };
  99433. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99434. this._scene = scene;
  99435. this.onErrorObservable = new BABYLON.Observable();
  99436. this._setupBackground();
  99437. this._setupImageProcessing();
  99438. }
  99439. /**
  99440. * Creates the default options for the helper.
  99441. */
  99442. EnvironmentHelper._getDefaultOptions = function () {
  99443. return {
  99444. createGround: true,
  99445. groundSize: 15,
  99446. groundTexture: this._groundTextureCDNUrl,
  99447. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99448. groundOpacity: 0.9,
  99449. enableGroundShadow: true,
  99450. groundShadowLevel: 0.5,
  99451. enableGroundMirror: false,
  99452. groundMirrorSizeRatio: 0.3,
  99453. groundMirrorBlurKernel: 64,
  99454. groundMirrorAmount: 1,
  99455. groundMirrorFresnelWeight: 1,
  99456. groundMirrorFallOffDistance: 0,
  99457. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99458. groundYBias: 0.00001,
  99459. createSkybox: true,
  99460. skyboxSize: 20,
  99461. skyboxTexture: this._skyboxTextureCDNUrl,
  99462. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99463. backgroundYRotation: 0,
  99464. sizeAuto: true,
  99465. rootPosition: BABYLON.Vector3.Zero(),
  99466. setupImageProcessing: true,
  99467. environmentTexture: this._environmentTextureCDNUrl,
  99468. cameraExposure: 0.8,
  99469. cameraContrast: 1.2,
  99470. toneMappingEnabled: true,
  99471. };
  99472. };
  99473. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99474. /**
  99475. * Gets the root mesh created by the helper.
  99476. */
  99477. get: function () {
  99478. return this._rootMesh;
  99479. },
  99480. enumerable: true,
  99481. configurable: true
  99482. });
  99483. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99484. /**
  99485. * Gets the skybox created by the helper.
  99486. */
  99487. get: function () {
  99488. return this._skybox;
  99489. },
  99490. enumerable: true,
  99491. configurable: true
  99492. });
  99493. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99494. /**
  99495. * Gets the skybox texture created by the helper.
  99496. */
  99497. get: function () {
  99498. return this._skyboxTexture;
  99499. },
  99500. enumerable: true,
  99501. configurable: true
  99502. });
  99503. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99504. /**
  99505. * Gets the skybox material created by the helper.
  99506. */
  99507. get: function () {
  99508. return this._skyboxMaterial;
  99509. },
  99510. enumerable: true,
  99511. configurable: true
  99512. });
  99513. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99514. /**
  99515. * Gets the ground mesh created by the helper.
  99516. */
  99517. get: function () {
  99518. return this._ground;
  99519. },
  99520. enumerable: true,
  99521. configurable: true
  99522. });
  99523. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99524. /**
  99525. * Gets the ground texture created by the helper.
  99526. */
  99527. get: function () {
  99528. return this._groundTexture;
  99529. },
  99530. enumerable: true,
  99531. configurable: true
  99532. });
  99533. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99534. /**
  99535. * Gets the ground mirror created by the helper.
  99536. */
  99537. get: function () {
  99538. return this._groundMirror;
  99539. },
  99540. enumerable: true,
  99541. configurable: true
  99542. });
  99543. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  99544. /**
  99545. * Gets the ground mirror render list to helps pushing the meshes
  99546. * you wish in the ground reflection.
  99547. */
  99548. get: function () {
  99549. if (this._groundMirror) {
  99550. return this._groundMirror.renderList;
  99551. }
  99552. return null;
  99553. },
  99554. enumerable: true,
  99555. configurable: true
  99556. });
  99557. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  99558. /**
  99559. * Gets the ground material created by the helper.
  99560. */
  99561. get: function () {
  99562. return this._groundMaterial;
  99563. },
  99564. enumerable: true,
  99565. configurable: true
  99566. });
  99567. /**
  99568. * Updates the background according to the new options
  99569. * @param options
  99570. */
  99571. EnvironmentHelper.prototype.updateOptions = function (options) {
  99572. var newOptions = __assign({}, this._options, options);
  99573. if (this._ground && !newOptions.createGround) {
  99574. this._ground.dispose();
  99575. this._ground = null;
  99576. }
  99577. if (this._groundMaterial && !newOptions.createGround) {
  99578. this._groundMaterial.dispose();
  99579. this._groundMaterial = null;
  99580. }
  99581. if (this._groundTexture) {
  99582. if (this._options.groundTexture != newOptions.groundTexture) {
  99583. this._groundTexture.dispose();
  99584. this._groundTexture = null;
  99585. }
  99586. }
  99587. if (this._skybox && !newOptions.createSkybox) {
  99588. this._skybox.dispose();
  99589. this._skybox = null;
  99590. }
  99591. if (this._skyboxMaterial && !newOptions.createSkybox) {
  99592. this._skyboxMaterial.dispose();
  99593. this._skyboxMaterial = null;
  99594. }
  99595. if (this._skyboxTexture) {
  99596. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  99597. this._skyboxTexture.dispose();
  99598. this._skyboxTexture = null;
  99599. }
  99600. }
  99601. if (this._groundMirror && !newOptions.enableGroundMirror) {
  99602. this._groundMirror.dispose();
  99603. this._groundMirror = null;
  99604. }
  99605. if (this._scene.environmentTexture) {
  99606. if (this._options.environmentTexture != newOptions.environmentTexture) {
  99607. this._scene.environmentTexture.dispose();
  99608. }
  99609. }
  99610. this._options = newOptions;
  99611. this._setupBackground();
  99612. this._setupImageProcessing();
  99613. };
  99614. /**
  99615. * Sets the primary color of all the available elements.
  99616. * @param color the main color to affect to the ground and the background
  99617. */
  99618. EnvironmentHelper.prototype.setMainColor = function (color) {
  99619. if (this.groundMaterial) {
  99620. this.groundMaterial.primaryColor = color;
  99621. }
  99622. if (this.skyboxMaterial) {
  99623. this.skyboxMaterial.primaryColor = color;
  99624. }
  99625. if (this.groundMirror) {
  99626. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  99627. }
  99628. };
  99629. /**
  99630. * Setup the image processing according to the specified options.
  99631. */
  99632. EnvironmentHelper.prototype._setupImageProcessing = function () {
  99633. if (this._options.setupImageProcessing) {
  99634. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  99635. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  99636. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  99637. this._setupEnvironmentTexture();
  99638. }
  99639. };
  99640. /**
  99641. * Setup the environment texture according to the specified options.
  99642. */
  99643. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  99644. if (this._scene.environmentTexture) {
  99645. return;
  99646. }
  99647. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  99648. this._scene.environmentTexture = this._options.environmentTexture;
  99649. return;
  99650. }
  99651. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  99652. this._scene.environmentTexture = environmentTexture;
  99653. };
  99654. /**
  99655. * Setup the background according to the specified options.
  99656. */
  99657. EnvironmentHelper.prototype._setupBackground = function () {
  99658. if (!this._rootMesh) {
  99659. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  99660. }
  99661. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  99662. var sceneSize = this._getSceneSize();
  99663. if (this._options.createGround) {
  99664. this._setupGround(sceneSize);
  99665. this._setupGroundMaterial();
  99666. this._setupGroundDiffuseTexture();
  99667. if (this._options.enableGroundMirror) {
  99668. this._setupGroundMirrorTexture(sceneSize);
  99669. }
  99670. this._setupMirrorInGroundMaterial();
  99671. }
  99672. if (this._options.createSkybox) {
  99673. this._setupSkybox(sceneSize);
  99674. this._setupSkyboxMaterial();
  99675. this._setupSkyboxReflectionTexture();
  99676. }
  99677. this._rootMesh.position.x = sceneSize.rootPosition.x;
  99678. this._rootMesh.position.z = sceneSize.rootPosition.z;
  99679. this._rootMesh.position.y = sceneSize.rootPosition.y;
  99680. };
  99681. /**
  99682. * Get the scene sizes according to the setup.
  99683. */
  99684. EnvironmentHelper.prototype._getSceneSize = function () {
  99685. var _this = this;
  99686. var groundSize = this._options.groundSize;
  99687. var skyboxSize = this._options.skyboxSize;
  99688. var rootPosition = this._options.rootPosition;
  99689. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  99690. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99691. }
  99692. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  99693. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  99694. });
  99695. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  99696. if (this._options.sizeAuto) {
  99697. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  99698. this._scene.activeCamera.upperRadiusLimit) {
  99699. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  99700. skyboxSize = groundSize;
  99701. }
  99702. var sceneDiagonalLenght = sceneDiagonal.length();
  99703. if (sceneDiagonalLenght > groundSize) {
  99704. groundSize = sceneDiagonalLenght * 2;
  99705. skyboxSize = groundSize;
  99706. }
  99707. // 10 % bigger.
  99708. groundSize *= 1.1;
  99709. skyboxSize *= 1.5;
  99710. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  99711. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  99712. }
  99713. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99714. };
  99715. /**
  99716. * Setup the ground according to the specified options.
  99717. */
  99718. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  99719. var _this = this;
  99720. if (!this._ground) {
  99721. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  99722. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  99723. this._ground.parent = this._rootMesh;
  99724. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  99725. }
  99726. this._ground.receiveShadows = this._options.enableGroundShadow;
  99727. };
  99728. /**
  99729. * Setup the ground material according to the specified options.
  99730. */
  99731. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  99732. if (!this._groundMaterial) {
  99733. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  99734. }
  99735. this._groundMaterial.alpha = this._options.groundOpacity;
  99736. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  99737. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  99738. this._groundMaterial.primaryColor = this._options.groundColor;
  99739. this._groundMaterial.useRGBColor = false;
  99740. this._groundMaterial.enableNoise = true;
  99741. if (this._ground) {
  99742. this._ground.material = this._groundMaterial;
  99743. }
  99744. };
  99745. /**
  99746. * Setup the ground diffuse texture according to the specified options.
  99747. */
  99748. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  99749. if (!this._groundMaterial) {
  99750. return;
  99751. }
  99752. if (this._groundTexture) {
  99753. return;
  99754. }
  99755. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  99756. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  99757. return;
  99758. }
  99759. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99760. diffuseTexture.gammaSpace = false;
  99761. diffuseTexture.hasAlpha = true;
  99762. this._groundMaterial.diffuseTexture = diffuseTexture;
  99763. };
  99764. /**
  99765. * Setup the ground mirror texture according to the specified options.
  99766. */
  99767. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  99768. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99769. if (!this._groundMirror) {
  99770. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  99771. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  99772. this._groundMirror.anisotropicFilteringLevel = 1;
  99773. this._groundMirror.wrapU = wrapping;
  99774. this._groundMirror.wrapV = wrapping;
  99775. this._groundMirror.gammaSpace = false;
  99776. if (this._groundMirror.renderList) {
  99777. for (var i = 0; i < this._scene.meshes.length; i++) {
  99778. var mesh = this._scene.meshes[i];
  99779. if (mesh !== this._ground &&
  99780. mesh !== this._skybox &&
  99781. mesh !== this._rootMesh) {
  99782. this._groundMirror.renderList.push(mesh);
  99783. }
  99784. }
  99785. }
  99786. }
  99787. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  99788. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  99789. };
  99790. /**
  99791. * Setup the ground to receive the mirror texture.
  99792. */
  99793. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  99794. if (this._groundMaterial) {
  99795. this._groundMaterial.reflectionTexture = this._groundMirror;
  99796. this._groundMaterial.reflectionFresnel = true;
  99797. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  99798. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  99799. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  99800. }
  99801. };
  99802. /**
  99803. * Setup the skybox according to the specified options.
  99804. */
  99805. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  99806. var _this = this;
  99807. if (!this._skybox) {
  99808. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  99809. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  99810. }
  99811. this._skybox.parent = this._rootMesh;
  99812. };
  99813. /**
  99814. * Setup the skybox material according to the specified options.
  99815. */
  99816. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  99817. if (!this._skybox) {
  99818. return;
  99819. }
  99820. if (!this._skyboxMaterial) {
  99821. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  99822. }
  99823. this._skyboxMaterial.useRGBColor = false;
  99824. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  99825. this._skyboxMaterial.enableNoise = true;
  99826. this._skybox.material = this._skyboxMaterial;
  99827. };
  99828. /**
  99829. * Setup the skybox reflection texture according to the specified options.
  99830. */
  99831. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  99832. if (!this._skyboxMaterial) {
  99833. return;
  99834. }
  99835. if (this._skyboxTexture) {
  99836. return;
  99837. }
  99838. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  99839. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  99840. return;
  99841. }
  99842. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99843. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  99844. this._skyboxTexture.gammaSpace = false;
  99845. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  99846. };
  99847. /**
  99848. * Dispose all the elements created by the Helper.
  99849. */
  99850. EnvironmentHelper.prototype.dispose = function () {
  99851. if (this._groundMaterial) {
  99852. this._groundMaterial.dispose(true, true);
  99853. }
  99854. if (this._skyboxMaterial) {
  99855. this._skyboxMaterial.dispose(true, true);
  99856. }
  99857. this._rootMesh.dispose(false);
  99858. };
  99859. /**
  99860. * Default ground texture URL.
  99861. */
  99862. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  99863. /**
  99864. * Default skybox texture URL.
  99865. */
  99866. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  99867. /**
  99868. * Default environment texture URL.
  99869. */
  99870. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  99871. return EnvironmentHelper;
  99872. }());
  99873. BABYLON.EnvironmentHelper = EnvironmentHelper;
  99874. })(BABYLON || (BABYLON = {}));
  99875. //# sourceMappingURL=babylon.environmentHelper.js.map
  99876. var BABYLON;
  99877. (function (BABYLON) {
  99878. /**
  99879. * This class is made for on one-liner static method to help creating particle systems.
  99880. */
  99881. var ParticleHelper = /** @class */ (function () {
  99882. function ParticleHelper() {
  99883. }
  99884. /**
  99885. * This is the main static method (one-liner) of this helper to create different particle systems.
  99886. * @param type This string represents the type to the particle system to create
  99887. * @param emitter The object where the particle system will start to emit from.
  99888. * @param scene The scene where the particle system should live.
  99889. * @param gpu If the system will use gpu.
  99890. * @returns the ParticleSystem created.
  99891. */
  99892. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  99893. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  99894. if (gpu === void 0) { gpu = false; }
  99895. return new Promise(function (resolve, reject) {
  99896. if (!scene) {
  99897. scene = BABYLON.Engine.LastCreatedScene;
  99898. ;
  99899. }
  99900. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  99901. return reject("Particle system with GPU is not supported.");
  99902. }
  99903. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  99904. var newData = JSON.parse(data.toString());
  99905. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  99906. }, undefined, undefined, undefined, function (req, exception) {
  99907. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  99908. });
  99909. });
  99910. };
  99911. /**
  99912. * Static function used to create a new particle system from a IParticleSystemData
  99913. * @param data defines the source data
  99914. * @param scene defines the hosting scene
  99915. * @param emitter defines the particle emitter
  99916. * @returns a new ParticleSystem based on referenced data
  99917. */
  99918. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  99919. // Create a particle system
  99920. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  99921. // Where the particles come from
  99922. system.emitter = emitter; // the starting object, the emitter
  99923. ParticleHelper.UpdateSystem(system, data, scene);
  99924. return system;
  99925. };
  99926. /**
  99927. * Static function used to update a particle system from a IParticleSystemData
  99928. * @param system defines the particle system to update
  99929. * @param data defines the source data
  99930. * @param scene defines the hosting scene
  99931. */
  99932. ParticleHelper.UpdateSystem = function (system, data, scene) {
  99933. // Texture of each particle
  99934. if (data.textureFile) {
  99935. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  99936. }
  99937. // Colors of all particles
  99938. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  99939. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  99940. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  99941. // Size of each particle (random between...
  99942. system.minSize = data.minSize;
  99943. system.maxSize = data.maxSize;
  99944. system.minScaleX = data.minScaleX;
  99945. system.maxScaleX = data.maxScaleX;
  99946. system.minScaleY = data.minScaleY;
  99947. system.maxScaleY = data.maxScaleY;
  99948. // Life time of each particle (random between...
  99949. system.minLifeTime = data.minLifeTime;
  99950. system.maxLifeTime = data.maxLifeTime;
  99951. // Emission rate
  99952. system.emitRate = data.emitRate;
  99953. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  99954. system.blendMode = data.blendMode;
  99955. // Set the gravity of all particles
  99956. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  99957. // Angular speed, in radians
  99958. system.minAngularSpeed = data.minAngularSpeed;
  99959. system.maxAngularSpeed = data.maxAngularSpeed;
  99960. // Speed
  99961. system.minEmitPower = data.minEmitPower;
  99962. system.maxEmitPower = data.maxEmitPower;
  99963. system.updateSpeed = data.updateSpeed;
  99964. switch (data.emitterType) {
  99965. case "box":
  99966. if (!data.direction1 || !data.direction2) {
  99967. throw new Error("Directions are missing in this particle system.");
  99968. }
  99969. if (!data.minEmitBox || !data.maxEmitBox) {
  99970. throw new Error("EmitBox is missing in this particle system.");
  99971. }
  99972. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  99973. break;
  99974. case "sphere":
  99975. system.createSphereEmitter(data.radius);
  99976. break;
  99977. case "directed_sphere":
  99978. if (!data.direction1 || !data.direction2) {
  99979. throw new Error("Directions are missing in this particle system.");
  99980. }
  99981. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  99982. break;
  99983. case "cone":
  99984. system.createConeEmitter(data.radius, data.angle);
  99985. break;
  99986. default:
  99987. break;
  99988. }
  99989. };
  99990. /**
  99991. * Static function used to export a particle system to a IParticleSystemData variable.
  99992. * Please note that texture file name is not exported and must be added manually
  99993. * @param system defines the particle system to export
  99994. */
  99995. ParticleHelper.ExportSystem = function (system) {
  99996. var outData = {};
  99997. // Colors of all particles
  99998. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  99999. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  100000. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  100001. // Size of each particle (random between...
  100002. outData.minSize = system.minSize;
  100003. outData.maxSize = system.maxSize;
  100004. outData.minScaleX = system.minScaleX;
  100005. outData.maxScaleX = system.maxScaleX;
  100006. outData.minScaleY = system.minScaleY;
  100007. outData.maxScaleY = system.maxScaleY;
  100008. // Life time of each particle (random between...
  100009. outData.minLifeTime = system.minLifeTime;
  100010. outData.maxLifeTime = system.maxLifeTime;
  100011. // Emission rate
  100012. outData.emitRate = system.emitRate;
  100013. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100014. outData.blendMode = system.blendMode;
  100015. // Set the gravity of all particles
  100016. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  100017. // Angular speed, in radians
  100018. outData.minAngularSpeed = system.minAngularSpeed;
  100019. outData.maxAngularSpeed = system.maxAngularSpeed;
  100020. // Speed
  100021. outData.minEmitPower = system.minEmitPower;
  100022. outData.maxEmitPower = system.maxEmitPower;
  100023. outData.updateSpeed = system.updateSpeed;
  100024. switch (system.particleEmitterType.getClassName()) {
  100025. case "BoxEmitter":
  100026. outData.emitterType = "box";
  100027. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  100028. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  100029. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  100030. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  100031. break;
  100032. case "SphereParticleEmitter":
  100033. outData.emitterType = "sphere";
  100034. outData.radius = system.particleEmitterType.radius;
  100035. break;
  100036. case "SphereDirectedParticleEmitter":
  100037. outData.emitterType = "directed_sphere";
  100038. var sphereDirectedParticleEmitter = system.particleEmitterType;
  100039. outData.radius = sphereDirectedParticleEmitter.radius;
  100040. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  100041. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  100042. break;
  100043. case "ConeEmitter":
  100044. outData.emitterType = "cone";
  100045. outData.radius = system.particleEmitterType.radius;
  100046. outData.angle = system.particleEmitterType.angle;
  100047. break;
  100048. default:
  100049. break;
  100050. }
  100051. return outData;
  100052. };
  100053. /**
  100054. * Base Assets URL.
  100055. */
  100056. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  100057. return ParticleHelper;
  100058. }());
  100059. BABYLON.ParticleHelper = ParticleHelper;
  100060. })(BABYLON || (BABYLON = {}));
  100061. //# sourceMappingURL=babylon.particleHelper.js.map
  100062. var BABYLON;
  100063. (function (BABYLON) {
  100064. /**
  100065. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  100066. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  100067. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  100068. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100069. */
  100070. var VideoDome = /** @class */ (function (_super) {
  100071. __extends(VideoDome, _super);
  100072. /**
  100073. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  100074. * @param name Element's name, child elements will append suffixes for their own names.
  100075. * @param urlsOrVideo defines the url(s) or the video element to use
  100076. * @param options An object containing optional or exposed sub element properties
  100077. */
  100078. function VideoDome(name, urlsOrVideo, options, scene) {
  100079. var _this = _super.call(this, name, scene) || this;
  100080. // set defaults and manage values
  100081. name = name || "videoDome";
  100082. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100083. options.clickToPlay = Boolean(options.clickToPlay);
  100084. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  100085. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  100086. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100087. // create
  100088. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  100089. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100090. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  100091. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100092. flat: false,
  100093. radius: options.size,
  100094. subdivisions: options.resolution,
  100095. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100096. }, scene);
  100097. // configure material
  100098. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100099. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100100. material.reflectionTexture = _this._videoTexture;
  100101. material.useEquirectangularFOV = true;
  100102. material.fovMultiplier = 1.0;
  100103. // configure mesh
  100104. _this._mesh.material = material;
  100105. _this._mesh.parent = _this;
  100106. // optional configuration
  100107. if (options.clickToPlay) {
  100108. scene.onPointerUp = function () {
  100109. _this._videoTexture.video.play();
  100110. };
  100111. }
  100112. return _this;
  100113. }
  100114. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  100115. /**
  100116. * Gets the video texture being displayed on the sphere
  100117. */
  100118. get: function () {
  100119. return this._videoTexture;
  100120. },
  100121. enumerable: true,
  100122. configurable: true
  100123. });
  100124. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  100125. /**
  100126. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100127. * Also see the options.resolution property.
  100128. */
  100129. get: function () {
  100130. return this._material.fovMultiplier;
  100131. },
  100132. set: function (value) {
  100133. this._material.fovMultiplier = value;
  100134. },
  100135. enumerable: true,
  100136. configurable: true
  100137. });
  100138. /**
  100139. * Releases resources associated with this node.
  100140. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100141. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100142. */
  100143. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100144. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100145. this._videoTexture.dispose();
  100146. this._mesh.dispose();
  100147. this._material.dispose();
  100148. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100149. };
  100150. return VideoDome;
  100151. }(BABYLON.Node));
  100152. BABYLON.VideoDome = VideoDome;
  100153. })(BABYLON || (BABYLON = {}));
  100154. //# sourceMappingURL=babylon.videoDome.js.map
  100155. var BABYLON;
  100156. (function (BABYLON) {
  100157. /**
  100158. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  100159. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  100160. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  100161. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100162. */
  100163. var PhotoDome = /** @class */ (function (_super) {
  100164. __extends(PhotoDome, _super);
  100165. /**
  100166. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  100167. * @param name Element's name, child elements will append suffixes for their own names.
  100168. * @param urlsOfPhoto define the url of the photo to display
  100169. * @param options An object containing optional or exposed sub element properties
  100170. */
  100171. function PhotoDome(name, urlOfPhoto, options, scene) {
  100172. var _this = _super.call(this, name, scene) || this;
  100173. // set defaults and manage values
  100174. name = name || "photoDome";
  100175. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100176. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100177. // create
  100178. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100179. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  100180. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100181. flat: false,
  100182. radius: options.size,
  100183. subdivisions: options.resolution,
  100184. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100185. }, scene);
  100186. // configure material
  100187. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100188. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100189. material.reflectionTexture = _this._photoTexture;
  100190. material.useEquirectangularFOV = true;
  100191. material.fovMultiplier = 1.0;
  100192. // configure mesh
  100193. _this._mesh.material = material;
  100194. _this._mesh.parent = _this;
  100195. return _this;
  100196. }
  100197. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  100198. /**
  100199. * Gets the texture being displayed on the sphere
  100200. */
  100201. get: function () {
  100202. return this._photoTexture;
  100203. },
  100204. enumerable: true,
  100205. configurable: true
  100206. });
  100207. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100208. /**
  100209. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100210. * Also see the options.resolution property.
  100211. */
  100212. get: function () {
  100213. return this._material.fovMultiplier;
  100214. },
  100215. set: function (value) {
  100216. this._material.fovMultiplier = value;
  100217. },
  100218. enumerable: true,
  100219. configurable: true
  100220. });
  100221. /**
  100222. * Releases resources associated with this node.
  100223. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100224. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100225. */
  100226. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100227. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100228. this._photoTexture.dispose();
  100229. this._mesh.dispose();
  100230. this._material.dispose();
  100231. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100232. };
  100233. return PhotoDome;
  100234. }(BABYLON.Node));
  100235. BABYLON.PhotoDome = PhotoDome;
  100236. })(BABYLON || (BABYLON = {}));
  100237. //# sourceMappingURL=babylon.photoDome.js.map
  100238. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec3 options;\nattribute vec2 size;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=options.x;\nvec2 offset=options.yz;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\nvec2 cornerPos=offset*size.yz*size.x;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin vec3 size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout vec3 outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=vec3(0.,0.,0.);\noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  100239. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  100240. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  100241. globalObject["BABYLON"] = BABYLON;
  100242. //backwards compatibility
  100243. if(typeof earcut !== 'undefined') {
  100244. globalObject["Earcut"] = {
  100245. earcut: earcut
  100246. };
  100247. }
  100248. return BABYLON;
  100249. });